How to add custom validation in fastapi?

Member

by domenico , in category: Third Party Scripts , 3 months ago

How to add custom validation in fastapi?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by adan , 3 months ago

@domenico 

To add custom validation in FastAPI, you can use Pydantic models and write custom validation methods within the model class. Here is an example of how you can add custom validation:

  1. Import the required modules:
1
2
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, validator


  1. Create a Pydantic model with custom validation methods:
1
2
3
4
5
6
7
8
9
class Item(BaseModel):
    name: str
    price: float

    @validator('price')
    def check_price(cls, value):
        if value < 0:
            raise ValueError('Price must be greater than 0')
        return value


In the above example, a custom validation method check_price is defined for the price field. The method checks if the price is greater than 0 and raises a ValueError if it is not.

  1. Use the Pydantic model in your FastAPI endpoint:
1
2
3
4
5
app = FastAPI()

@app.post('/items/')
async def create_item(item: Item):
    return {'name': item.name, 'price': item.price}


In this example, the create_item endpoint receives a POST request with a JSON payload that conforms to the Item model. If the custom validation fails, FastAPI will automatically return a 422 Unprocessable Entity response with details of the validation error.


By using Pydantic models and custom validation methods, you can easily add custom validation to your FastAPI application.

Related Threads:

How to add custom form validation in laravel?
How to add a custom decorator to a fastapi route?
How to set custom validation message in laravel?
How to create custom validation helpers in CakePHP?
How to use custom validation message in laravel?
How to add password matching validation in vuetify?