
FastAPI
Let's build and run your first working FastAPI endpoint in just a few minutes.
Install FastAPI and Uvicorn:
pip install fastapi uvicornCreate `main.py`:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello, World!"}uvicorn main:app --reloadVisit `http://localhost:8000` in your browser. You'll see your JSON response!
| Component | Meaning |
|---|---|
| `app = FastAPI()` | Creates the API application |
| `@app.get("/")` | Creates a GET endpoint at root |
| `async def` | Async function for concurrent requests |
| `return {...}` | JSON response sent to client |
Visit `http://localhost:8000/docs` to see Swagger UI where you can:
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: float
@app.get("/items")
async def list_items():
return [{"id": 1, "name": "Item 1", "price": 10.0}]
@app.post("/items")
async def create_item(item: Item):
return {"id": 2, **item.dict()}
@app.get("/items/{item_id}")
async def get_item(item_id: int):
return {"id": item_id, "name": "Item", "price": 10.0}Use Pydantic to define request/response structure:
from pydantic import BaseModel, Field
class User(BaseModel):
name: str = Field(..., min_length=1, max_length=100)
email: str
age: int = Field(..., ge=0, le=150)
is_active: bool = True| Method | Purpose | Example |
|---|---|---|
| GET | Retrieve data | List items |
| POST | Create data | Create new item |
| PUT | Replace data | Replace entire item |
| DELETE | Remove data | Delete item |
| PATCH | Update data | Partial update |
Use `curl` to test:
# GET request
curl http://localhost:8000/items/1
# POST request
curl -X POST http://localhost:8000/items \
-H "Content-Type: application/json" \
-d '{"name":"New Item","price":25.0}'Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep • Build Real • Verify Skills • Launch Forward