Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

FastAPI - set arbitrary header in response

from fastapi import FastAPI, Response

app = FastAPI()


@app.get("/")
async def main(response: Response):
    response.headers['X-something-else'] = "some value"
    return {"message": "Hello World"}

from fastapi.testclient import TestClient

from main import app

client = TestClient(app)


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