Data Validation
-
FastApi uses pydantic
-
Create a simple file models.py
from pydantic import BaseModel
class ProductResponse(BaseModel):
name: str
price: float
description: str
class ProductRequest(ProductResponse):
id: int
- Use this schema in main.py
from fastapi import FastAPI, status
from models import ProductRequest, ProductResponse
# create an application object
app = FastAPI()
@app.get("/")
def home():
return "Welcome to my API"
@app.get("/products")
def get_products() -> list[ProductResponse]:
responses = [
ProductResponse(name="Phone", price=100.0, description="This is a phone"),
ProductResponse(name="Laptop", price=1000.0, description="This is a laptop")
]
return responses
@app.post("/products", status_code=status.HTTP_201_CREATED)
def add_product(request: ProductRequest) -> ProductResponse:
return ProductResponse(**request.dict(), id=1)
@app.put("/products/{id}")
def update_product(id:int, name:str):
return {"id": id, "name": name}
@app.get("/customers")
def get_customers():
return [
{"id": 1, "name": "John"},
{"id": 2, "name": "Jane"}
]
@app.delete("/products/{id}")
def delete_product(id: int):
raise NotImplementedError()
- We can add validations
from pydantic import BaseModel, Field, HttpUrl
class ProductResponse(BaseModel):
name: str = Field(max_length=15)
price: float = Field(gt=0)
description: str
url: HttpUrl
class ProductRequest(ProductResponse):
id: int
- Exercise:
- For the user apis create a schema with first name, last name, age, email, phone numbers with validations, aadhar number, credit card number
- Ensure you test all of the above from postman
