Is it possible to generate openapi.json with "nullable" : "true" for non-required property?
I'm using NSwag to generate C# code from FastAPI openapi.json. I need to set "nullable" as "true" to make it work correctly.
I have a FastAPI Model like this:
class Topic(BaseModel):
first_id: str = None
I want to get a schema like this:
"Topic": {
"title": "Topic",
"type": "object",
"properties": {
"first_id": {
"title": "First_Id",
"type": "string",
"nullable" : "true"
}
}
}
But I haven't found a way to set the field "nullable". And if it's not provided, it is "false" by default.
You can use Field to set nullable=True by default.
Example:
from fastapi import FastAPI, Depends, Query, HTTPException
from typing import Optional
from pydantic import BaseModel, Field
app = FastAPI()
class Model(BaseModel):
a: Optional[int]
b: Optional[int] = None
c: Optional[int] = Field(None, nullable=True)
@app.get("/test", response_model=Model)
def foo(m: Model):
return m
Component in /openapi.json
...
Model: {
title: "Model",
required: [
"c"
],
type: "object",
properties: {
a: {
title: "A",
type: "integer"
},
b: {
title: "B",
type: "integer"
},
c: {
title: "C",
type: "integer",
nullable: true
}
}
...
@Slyfoxy Thanks for answer, it helped!
I found out, that Field is not working with FastAPI
But Schema did the job!
from pydantic import BaseModel, Schema
class Topic(BaseModel):
first_id: str = Schema(None, nullable=True)
And /openapi.json
"Topic": {
"title": "Topic",
"type": "object",
"properties": {
"first_id": {
"title": "First_Id",
"type": "string",
"nullable": true
}
}
}
Fastapi works with 'Field' from 'pydantic' in latest version of 'fastapi' with 'pydantic=1.0'. Just update it :)
Ah, ok, understood!
Thank you :)
Thanks for the help here @Slyfoxy ! :cake: :bowing_man:
Thanks @dennismeissel for reporting back and closing the issue :+1:
Most helpful comment
You can use Field to set
nullable=Trueby default.Example:
Component in
/openapi.json