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.

[BUG] Unable to specify schema for specific media type if same as response_class

See original GitHub issue

Describe the bug

When the (inferred) response_class matches the media type key in responses, I can’t override the schema for that media type—it just uses the response_model value. The media type schema override does work for a media type that doesn’t match response_class.

To Reproduce

Steps to reproduce the behavior with a minimum self-contained file.

Replace each part with your own scenario:

  1. Create a file with:
from typing import Union, List
from enum import Enum

from fastapi import FastAPI, Header
from starlette import status
from pydantic import BaseModel, Field

app = FastAPI()


class DogsJson(BaseModel):
    dogs: list


class DogFeature(BaseModel):
    type: str = Field("Feature", const=True)
    geometry: dict
    properties: dict


class DogsGeoJson(BaseModel):
    features: List[DogFeature]


class DogsRequestAcceptHeaders(Enum):
    json = "application/json"
    geojson = "application/geo+json"


@app.post(
    "/dogs",
    response_model=Union[DogsJson, DogsGeoJson],
    responses={
        status.HTTP_200_OK: {
            "content": {
                DogsRequestAcceptHeaders.json.value: {
                    "schema": {
                        "$ref": f"#/components/schemas/{DogsJson.__name__}"
                    }
                },
                DogsRequestAcceptHeaders.geojson.value: {
                    "schema": {
                        "$ref": f"#/components/schemas/{DogsGeoJson.__name__}"
                    }
                },
            }
        },
    },
)
async def get_dogs(
        accept: DogsRequestAcceptHeaders = Header(DogsRequestAcceptHeaders.json),
) -> Union[DogsJson, DogsGeoJson]:
    dogs = ["dog_1", "dog_2"]

    if accept == DogsRequestAcceptHeaders.json:
        return DogsJson(dogs=dogs)
    else:
        dog_features = [DogFeature(geometry={}, properties={"name": dog}) for dog in dogs]
        return DogsGeoJson(features=dog_features)


from uvicorn import run
run(app, host="localhost", port=8000)
  1. Open the browser at localhost:8000/docs.
  2. Inspect the 200 response for /dogs and note that media type application/json’s schema is still derived from response_model and not overridden by what’s in responses. Also note that application/geo+json is overridden as expected.

Expected behavior

OpenAPI schema declarations in responses should override any other conflicting definitions.

Screenshots

application/json schema matches response_model when it should match what’s in responses. Screen Shot 2020-02-07 at 10 25 17 AM

application/geo+json schema matches what’s in responses, as expected. Screen Shot 2020-02-07 at 10 25 29 AM

Environment

  • OS: macOS
  • FastAPI Version: 0.48.0
  • Python version: 3.8.1

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Reactions:1
  • Comments:5 (1 by maintainers)

github_iconTop GitHub Comments

1reaction
tiangolocommented, Dec 26, 2020

Thanks for the help here everyone! 👏 🙇

Thanks for reporting back and closing the issue @maflaven 👍

0reactions
maflavencommented, Sep 7, 2020

@eth3lbert yes this is fixed!

Read more comments on GitHub >

github_iconTop Results From Across the Web

SpringDoc for a complex response type - Stack Overflow
mediaType - Specifies the type of object that will be returned by the API. Mandatory to be specified, if a valid response is...
Read more >
SchemaId already used for different type #1607 - GitHub
Swashbuckle.AspNetCore should be able to re-use the same schema id for the same types, even if they're nested in different classes, right?
Read more >
Additional Responses in OpenAPI - FastAPI - tiangolo
A key with the media type, e.g. application/json , that contains as value ... the same media type as the main response class...
Read more >
Custom connector - Adding sample response data thr...
Custom connector - Adding sample response data throws error Unable to convert array of different types into schema. Reply. Topic Options.
Read more >
API — Flask Documentation (2.2.x)
The flask object implements a WSGI application and acts as the central object. It is passed the name of the module or package...
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