Thursday, 19 May 2022

How to document default None/null in OpenAPI/Swagger using FastAPI?

Using a ORM, I want to do a POST request letting some fields with a null value, which will be translated in the database for the default value specified there.

The problem is that OpenAPI (Swagger) docs, ignores the default None and still prompts a UUID by default.

from fastapi import FastAPI
from pydantic import BaseModel
from typing import Optional
from uuid import UUID
import uvicorn


class Table(BaseModel):
    # ID: Optional[UUID]      # the docs show a example UUID, ok
    ID: Optional[UUID] = None # the docs still shows a uuid, when it should show a null or valid None value.

app = FastAPI()  
    
@app.post("/table/", response_model=Table)
def create_table(table: Table):
    # here we call to sqlalchey orm etc.
    return 'nothing important, the important thing is in the docs'
    
if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)

In the OpenAPI schema example (request body) which is at the docs we find:

{
 "ID": "3fa85f64-5717-4562-b3fc-2c963f66afa6"
}

This is not ok, because I specified that the default value is None,so I expected this instead:

{
 "ID": null, # null is the equivalent of None here
}

Which will pass a null to the ID and finally will be parsed in the db to the default value (that is a new generated UUID).



from How to document default None/null in OpenAPI/Swagger using FastAPI?

No comments:

Post a Comment