Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

REST API in Python with FastAPI and pydantic: read-only property in model

Assume a REST API which defines a POST method on a resource /foos to create a new Foo. When creating a Foo the name of the Foo is an input parameter (present in the request body). When the server creates a Foo it assigns it an ID. This ID is returned together with the name in the REST response. I am looking for something similar to readOnly in OpenAPI.

The input JSON should look like this:

{
    "name": "bar"
}

The output JSON should look like that:

{
    "id": 123,
    "name": "bar"
}

Is there a way to reuse the same pydantic model? Or is it necessary to use two diffent models?

class FooIn(BaseModel):
    name: str

class Foo(BaseModel):
    id: int
    name: str

I cannot find any mentions of "read only", "read-only", or "readonly" in the pydantic documentation or in the Field class code.

Googling I found a post which mentions

id: int = Schema(..., readonly=True)

But that seems to have no effect in my use case.

like image 296
DrP3pp3r Avatar asked Aug 05 '26 05:08

DrP3pp3r


1 Answers

It is fine to have multiple models. You can use inheritance to reduce code repetition:

from pydantic import BaseModel


# Properties to receive via API create/update
class Foo(BaseModel):
    name: str


# Properties to return via API
class FooDB(Foo):
    id: int

The documentation which is excellent btw!, goes into this more in-depth.

Here is a real user model example taken from the official full stack project generator. You can see how there are multiple models to define the user schema depending on the context.

like image 53
michaeloliver Avatar answered Aug 07 '26 19:08

michaeloliver



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!