fastapi icon indicating copy to clipboard operation
fastapi copied to clipboard

Is it possible to generate openapi.json with "nullable" : "true" for non-required property?

Open dennismeissel opened this issue 6 years ago • 5 comments

Description

Is it possible to generate openapi.json with "nullable" : "true" for non-required property?

Additional context

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.

dennismeissel avatar Jan 08 '20 10:01 dennismeissel

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
	}
}
...

nkhitrov avatar Jan 21 '20 21:01 nkhitrov

@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
        }
    }
}

dennismeissel avatar Jan 23 '20 10:01 dennismeissel

Fastapi works with 'Field' from 'pydantic' in latest version of 'fastapi' with 'pydantic=1.0'. Just update it :)

nkhitrov avatar Jan 23 '20 10:01 nkhitrov

Ah, ok, understood!

Thank you :)

dennismeissel avatar Jan 23 '20 11:01 dennismeissel

Thanks for the help here @Slyfoxy ! :cake: :bowing_man:

Thanks @dennismeissel for reporting back and closing the issue :+1:

tiangolo avatar Apr 07 '20 17:04 tiangolo