Showing posts with label pydentic. Show all posts
Showing posts with label pydentic. Show all posts

Wednesday

Fast API with Pydentic

FastAPI and Pydantic are often used together to build APIs in Python. FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.7+ based on standard Python type hints. Pydantic is a data validation and settings management library that plays well with FastAPI. Here's a simple example:


Let's create an API using FastAPI with Pydantic for request and response models.


```python

from fastapi import FastAPI

from pydantic import BaseModel


app = FastAPI()


# Pydantic model for request

class Item(BaseModel):

    name: str

    description: str = None

    price: float

    quantity: int


# Pydantic model for response

class ItemResponse(BaseModel):

    name: str

    description: str = None


# Endpoint to create an item

@app.post("/items/", response_model=ItemResponse)

async def create_item(item: Item):

    return {"name": item.name, "description": item.description}


# Endpoint to read an item by name

@app.get("/items/{item_name}", response_model=ItemResponse)

async def read_item(item_name: str):

    return {"name": item_name, "description": "Item description"}


# Endpoint to update an item by name

@app.put("/items/{item_name}", response_model=ItemResponse)

async def update_item(item_name: str, item: Item):

    return {"name": item_name, "description": item.description}

```


In this example:

- We define a Pydantic model `Item` for request payload and another `ItemResponse` for the response payload.

- The `create_item` endpoint is for creating an item and expects an `Item` in the request body. It responds with an `ItemResponse`.

- The `read_item` endpoint is for reading an item by name and responds with an `ItemResponse`.

- The `update_item` endpoint is for updating an item by name and expects an `Item` in the request body. It responds with an `ItemResponse`.


FastAPI will automatically generate API documentation (using Swagger UI) based on the type hints and Pydantic models. This is a powerful combination for building robust and well-documented APIs in Python.