Skip to content
Advertisement

List of object attributes in pydantic model

I use Fast API to create a web service.

There are following sqlAlchemy models:

JavaScript

Pydantic schemas are below:

JavaScript

What I have now is:

JavaScript

What I want to achieve is to get user from api in following structure:

JavaScript

Is that possible? How should I change schemas to get this?

Advertisement

Answer

If you are okay with handling the how to “get user from api” problem statement by modifying the fastapi path definition, see below.

Can you change the response model used by the fastapi path definition in order to handle the desired output format?

Example pydantic response model definition:

JavaScript

Example sqlalchemy query + serialization function:

JavaScript

Example fastapi path definition:

JavaScript

Considerations:

  • I’m using a user_id for the user queries but this can be replaced with whatever you end up using as your primary key for that table.
  • The UserResponse response model is very similar to UserBase (you could potentially subclass UserBase instead of model to avoid the redefinition of account_name and email, with the tradeoff of having to override the class’ Config).
  • There may be a way to override the serialization format of the UserBase sqlalchemy model object that gets automatically serialized when you query the model from the database and allows you to eliminate or reduce the code in the get_user_response() function in the example definition above.
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement