Fix FastAPI "Invalid args for response field: check that class is a valid Pydantic field type" error

David Y.

The Problem

I’m seeing the error below when I run my FastAPI project:

fastapi.exceptions.FastAPIError: Invalid args for response field! Hint: check that <class 'main.User'> is a valid pydantic field type

My code looks like this:

from fastapi import FastAPI app = FastAPI() class User(): firstname: str surname: str age: int @app.post("/create-user/") async def create_user(user: User): # ... user creation operations ... return {"Message": "User created."}

What is going wrong and how do I fix it?

The Solution

FastAPI expects the values passed into its API route functions to be of types it recognizes. As FastAPI uses Pydantic to validate data types, any types we pass into route functions should inherit from Pydantic’s BaseModel class. Therefore, we can fix this error by making User inherit from BaseModel:

from fastapi import FastAPI from pydantic import BaseModel # import BaseModel app = FastAPI() class User(BaseModel): # inherit BaseModel firstname: str surname: str age: int @app.post("/create-user/") async def create_user(user: User): # ... user creation operations ... return {"Message": "User created."}

As an alternative, we could alter our create_user function to take the attributes of the User class as individual parameters:

from fastapi import FastAPI app = FastAPI() class User(): firstname: str surname: str age: int @app.post("/create-user/") async def create_user(firstname: str, surname: str, age: int): # ... user creation operations ... return {"Message": "User created."}

Pydantic already recognizes built-in types such as str and int, so this will work as expected. This approach may be useful when working with classes that do not inherit from BaseModel or when writing functions with inputs that do not correspond directly to a class’s attributes. However, for a function like this one, the first approach would be considered best practice, as it reduces code duplication and allows us to leverage Pydantic’s powerful data validation functionality for our custom class.

Loved by over 4 million developers and more than 90,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.

Share on Twitter
Bookmark this page
Ask a questionJoin the discussion

Related Answers

A better experience for your users. An easier life for your developers.

    TwitterGitHubDribbbleLinkedinDiscord
© 2024 • Sentry is a registered Trademark
of Functional Software, Inc.