Skip to content
Advertisement

How to disable schema checking in FastAPI?

I am migrating a service from Flask to FastAPI and using Pydantic models to generate the documentation. However, I’m a little unsure about the schema check. I’m afraid there will be some unexpected data (like a different field format) and it will return an error.

In the Pydantic documentation there are ways to create a model without checking the schema: https://pydantic-docs.helpmanual.io/usage/models/#creating-models-without-validation

However, as this is apparently instantiated by FastAPI itself, I don’t know how to disable this schema check when returning from FastAPI.

Advertisement

Answer

You could return Response directly, or with using custom responses for automatic convertion. In this case, response data is not validated against the response model. But you can still document it as described in Additional Responses in OpenAPI.

Example:

class SomeModel(BaseModel):
    num: int


@app.get("/get", response_model=SomeModel)
def handler(param: int):
    if param == 1:  # ok
        return {"num": "1"}
    elif param == 2:  # validation error
        return {"num": "not a number"}
    elif param == 3:  # ok (return without validation)
        return JSONResponse(content={"num": "not a number"})
    elif param == 4:  # ok (return without validation and conversion)
        return Response(content=json.dumps({"num": "not a number"}), media_type="application/json")
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement