question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Custom response does not include headers set in dependencies

See original GitHub issue

First Check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn’t find it.
  • I searched the FastAPI documentation, with the integrated search.
  • I already searched in Google “How to X in FastAPI” and didn’t find any information.
  • I already read and followed all the tutorial in the docs and didn’t find an answer.
  • I already checked if it is not related to FastAPI but to Pydantic.
  • I already checked if it is not related to FastAPI but to Swagger UI.
  • I already checked if it is not related to FastAPI but to ReDoc.

Commit to Help

  • I commit to help with one of those options 👆

Example Code

import fastapi


def set_custom_header(response: fastapi.Response) -> None:
    response.headers["X-Custom-Header"] = "Testing Response Dependencies"


app = fastapi.FastAPI(dependencies=[fastapi.Depends(set_custom_header)])


@app.get("/response")
def response():
    return {"status": "ok"}


@app.get("/custom_response")
def custom_response():
    return fastapi.responses.JSONResponse({"status": "ok"})

Description

When an endpoint returns an explicit Response headers set in dependencies are not set. However, if one returns the plain data and relies on the default response then the headers are included.

With the example code above, I one fetches /response then the header x-custom-header will be set, but not when using the endpoint /custom_response.

$ curl localhost:8000/response -v
> GET /response HTTP/1.1
> Host: localhost:8000
> User-Agent: curl/7.64.1
> Accept: */*
>
< HTTP/1.1 200 OK
< date: Sat, 15 Oct 2022 19:09:55 GMT
< server: uvicorn
< content-length: 15
< x-custom-header: Testing Responde dependencies
<
{"status":"ok"}


$ curl localhost:8000/custom_response -v
> GET /custom_response HTTP/1.1
> Host: localhost:8000
> User-Agent: curl/7.64.1
> Accept: */*
>
< HTTP/1.1 200 OK
< date: Sat, 15 Oct 2022 19:09:58 GMT
< server: uvicorn
< content-length: 15
<
{"status":"ok"}

The part where the headers are added to the default response is here

https://github.com/tiangolo/fastapi/blob/90fc4299d1d24a54dda8bf6f01cf3779ce6cf467/fastapi/routing.py#L263-L264

and here is the code where a custom response is returned

https://github.com/tiangolo/fastapi/blob/90fc4299d1d24a54dda8bf6f01cf3779ce6cf467/fastapi/routing.py#L235-L238

Operating System

macOS

Operating System Details

No response

FastAPI Version

0.79.0

Python Version

Python 3.10.8

Additional Context

No response

Issue Analytics

  • State:closed
  • Created a year ago
  • Comments:5 (3 by maintainers)

github_iconTop GitHub Comments

2reactions
jgould22commented, Oct 16, 2022

This feels like expected behavior.

You have edited the response object in the dependency and then created a fresh new response in your controller without the edited headers.

Anything you have done to the response object previously is thrown away in favor of your new response object.

If you wanted to be sure all responses get a header and not worry about the controller you could do it with an ASGI middle-ware which would add the header after the controller is run.

1reaction
tiangolocommented, Nov 9, 2022

Yep, as @jgould22 says, returning responses directly is a scape hatch for you to override anything FastAPI would do and take over directly: https://fastapi.tiangolo.com/advanced/response-directly/#return-a-response

They are not intended as the main use case. And yes, this means there are two ways to do things, do them through the normal ways, returning data directly, or taking over the wheel and doing things yourself. It’s not great to have two ways to do things, but there’s no other way to let you take the wheel, so we have to leave with that.

Maybe that section in the docs could include another note apart from saying that any data validation won’t be done, and also say that no additional headers or background tasks set in other places will be included. If you think that would make things clearer for you, please make a PR there to the docs with that extra note. 🙏

Read more comments on GitHub >

github_iconTop Results From Across the Web

Http response do not include headers · Issue #5237 - GitHub
Maybe i am doing something wrong but when i make a request with Http i can see on the Network tab on chrome...
Read more >
Spring boot does not seem to expose a custom header to my ...
I have added the following header to my GET-handler: httpHeaders.add(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, "filename"); . Now, this solves ...
Read more >
Response Headers - FastAPI - tiangolo
Have in mind that custom proprietary headers can be added using the 'X-' prefix. But if you have custom headers that you want...
Read more >
How to add default security headers in ASP.NET Core using ...
In this post I'm going to show how you can easily extend the existing middleware to add additional security headers, like X-Frame-Options, ...
Read more >
Create custom headers in backend services | Load Balancing
Custom request and response headers let you specify additional headers that the load balancer can add to HTTP(S) requests and responses.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found