Junior — Middle
How could you implement a REST API using FastAPI, considering the project requirements?
sobes.tech AI
Answer from AI
To implement a REST API using FastAPI, you need to follow several steps:
- Install FastAPI and an ASGI server, such as Uvicorn:
pip install fastapi uvicorn
-
Create a FastAPI application and define routes (endpoints) for handling HTTP requests (GET, POST, PUT, DELETE, etc.).
-
Use Pydantic models for data validation and serialization.
-
If necessary, connect to a database (e.g., via SQLAlchemy) and implement CRUD logic.
-
Run the server using Uvicorn.
Example of a simple API with one GET and POST endpoint:
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
id: int
name: str
items = {}
@app.get("/items/{item_id}")
async def read_item(item_id: int):
return items.get(item_id, {"error": "Item not found"})
@app.post("/items/")
async def create_item(item: Item):
items[item.id] = item
return item
Running:
uvicorn main:app --reload
This approach allows for quickly creating scalable and convenient REST APIs with automatic documentation (Swagger UI).