How to disallow empty parameters in fastapi?

by wilmer.lemke , in category: Javascript , 13 days ago

How to disallow empty parameters in fastapi?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by cortez.connelly , 12 days ago

@wilmer.lemke 

In FastAPI, you can use Python's type hints and set default values for parameters to disallow empty parameters. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str
    description: str

@app.post("/items/")
async def create_item(item: Item):
    if not item.name or not item.description:
        return {"message": "Name and description cannot be empty"}
    
    return {"name": item.name, "description": item.description}


In this example, the Item class defines the structure of the request payload using Pydantic models. By setting the name and description fields to be of type str, FastAPI will automatically validate the input and ensure that these fields are not empty.


Inside the create_item endpoint function, we can then check if the name and description fields are not empty and return an error message if they are.


This way, you can disallow empty parameters in FastAPI by using type hints and setting default values for parameters.