7

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.

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.