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.

Not getting user user given value for "Accept" header from swagger ui.

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

from fastapi import FastAPI, Header
from typing import Optional
import cv2
import io
import numpy as np
from fastapi.responses import StreamingResponse, JSONResponse

app = FastAPI()

@app.get("/image")
def get_image(accept: Optional[str] = Header("image/png")):
    accept_headers = accept.split(",")
    dummy = np.zeros((512, 512))
    if "image/png" in accept_headers or "*/*" in accept_headers:
        return StreamingResponse(
            io.BytesIO(cv2.imencode(".png", dummy)[1]), media_type="image/png"
        )
    elif "image/jpeg" in accept_headers:
        return StreamingResponse(
            io.BytesIO(cv2.imencode(".jpeg", dummy)[1]), media_type="image/jpeg"
        )
    else:
        return JSONResponse(
            status_code=406,
            content={
                "message": "encoding of type {} is not supported".format(accept)
            },
        )

Description

Hi, I have an API that is sending responses in different encoding depending on the user and to detect which encoding server should use I am using the “Accept” header. But when I tried to test it using Swagger UI, it always sent “application/json”.

Operating System

Linux, Windows

Operating System Details

No response

FastAPI Version

0.70.1

Python Version

Python 3.9.5

Additional Context

No response

Issue Analytics

  • State:open
  • Created 2 years ago
  • Reactions:1
  • Comments:8

github_iconTop GitHub Comments

1reaction
prateek9623commented, Jan 20, 2022

i already knew this api work from source other than swagger, but it would have been nice if it also worked on swagger.

0reactions
rafsafcommented, Jan 19, 2022

Observations:

  1. In this code, accept is overwritten by openapi docs as you observed:

    @app.get("/image")
    def get_image(accept: str = Header("image/png")):
        return StreamingResponse(
            io.BytesIO("test".encode()), media_type=accept
        )
    

    BUT if in terminal you type

    curl -X 'GET' \
      'http://localhost:8000/image' \
      -H 'accept: image/png'
    

    It works just fine for me.

  2. If then we change accept to custom_accept:

    @app.get("/image")
    def get_image(custom_accept: str = Header("image/png")):
        return StreamingResponse(
            io.BytesIO("test".encode()), media_type=custom_accept
        )
    

    You get working custom_accept header just as expected and docs are not broken.

Conclusions:

It’s not FastAPI related, not in any direct way I mean. I found something that may be interesting for you: https://github.com/swagger-api/swagger-ui/issues/7374

That’s kind of expected for me that your accept header will be overwritten by default one.

So, with any luck, you have 3 options:

  • either use custom header, in the end I think it’s acceptable solution
  • or read https://fastapi.tiangolo.com/advanced/extending-openapi/, read mentioned issue above and possible solution, extend/manipulate your OpenAPI schema and it should work.
  • if you don’t care about generated OpenAPI docs, just leave it as is, your endpoint will work, but docs will stay a bit not clean
Read more comments on GitHub >

github_iconTop Results From Across the Web

Swagger UI Not adding Header to Requests - Stack Overflow
I am using Swagger 2.0 and Swagger UI 3.0. 3. This adds an Authorize button the the Swagger UI where the user can...
Read more >
Describing Responses - Swagger
An API specification needs to specify the responses for all API operations. Each operation must have at least one response defined, usually a...
Read more >
API Keys - Swagger
Some APIs use API keys for authorization. ... or as a request header: ... (not to be confused with the API key name,...
Read more >
Cookie Authentication - Swagger
Note for Swagger UI and Swagger Editor users: Cookie authentication is currently not supported for "try it out" requests due to browser security ......
Read more >
Describing Parameters - Swagger
paths: /users/{userId}:; get: summary: Get a user by ID; parameters: ... Note: Header parameters named Accept , Content-Type and Authorization are not ......
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