FastAPI - get header from request



examples/fastapi/get-header/main.py
from fastapi import FastAPI, Request

app = FastAPI()


@app.get("/")
async def main(request: Request):
    print(request.headers)
    # Headers({
    #     'host': 'testserver',
    #     'user-agent': 'testclient',
    #     'accept-encoding': 'gzip, deflate',
    #     'accept': '*/*',
    #     'connection': 'keep-alive',
    #     'x-some-field': 'a value'
    # })

    #print(request.client)
    print(request.client.host) # testclient
    print(request.client.port) # 50000
    return {"message": "Hello World"}

examples/fastapi/get-header/test_main.py
from fastapi.testclient import TestClient

from main import app

client = TestClient(app)


def test_read_main():
    response = client.get("/", headers={"x-some-field": "a value"})
    assert response.status_code == 200
    assert response.json() == {"message": "Hello World"}
    assert response.headers == {'content-length': '25', 'content-type': 'application/json'}