In FastAPI, HTTP methods define what action the client wants to perform on a resource.
Think of a simple User Management API:
| Method | Purpose | Example |
|---|---|---|
| GET | Read data | Get user details |
| POST | Create new data | Create a new user |
| PUT | Update existing data | Update user information |
| DELETE | Remove data | Delete a user |
Used to retrieve data from the server.
from fastapi import FastAPI
app = FastAPI()
@app.get("/users/{user_id}")
def get_user(user_id: int):
return {"user_id": user_id, "name": "Abhishek"}
GET /users/1
{
"user_id": 1,
"name": "Abhishek"
}
✅ Fetch User
✅ Fetch Products
✅ Fetch Reports
Used to create new data.
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class User(BaseModel):
name: str
age: int
@app.post("/users")
def create_user(user: User):
return {
"message": "User created",
"data": user
}
{
"name": "Abhishek",
"age": 35
}
{
"message": "User created",
"data": {
"name": "Abhishek",
"age": 35
}
}
✅ Register User
✅ Upload File
✅ Create Order
Used to update an existing resource completely.
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class User(BaseModel):
name: str
age: int
@app.put("/users/{user_id}")
def update_user(user_id: int, user: User):
return {
"message": "User updated",
"user_id": user_id,
"data": user
}
PUT /users/1
Body:
{
"name": "Abhishek Agnihotri",
"age": 36
}
{
"message": "User updated",
"user_id": 1,
"data": {
"name": "Abhishek Agnihotri",
"age": 36
}
}
✅ Update Profile
✅ Update Product Details
✅ Update Employee Record
| Feature | GET | POST | PUT |
|---|---|---|---|
| Purpose | Read Data | Create Data | Update Data |
| Sends Body | Usually No | Yes | Yes |
| Changes Server Data | No | Yes | Yes |
| Idempotent* | Yes | No | Yes |
| Example | Get User | Create User | Update User |
An operation is idempotent if calling it multiple times gives the same result.
GET /users/1
GET /users/1
GET /users/1
Same data returned every time.
PUT /users/1
{
"name":"John"
}
Running it 10 times still leaves the user as:
{
"name":"John"
}
POST /users
{
"name":"John"
}
Running it 10 times creates 10 users.
@app.post("/users")
def create_user():
pass
@app.get("/users")
def get_users():
pass
@app.get("/users/{id}")
def get_user(id: int):
pass
@app.put("/users/{id}")
def update_user(id: int):
pass
@app.delete("/users/{id}")
def delete_user(id: int):
pass
This is the standard REST API pattern used in FastAPI applications.
@app.get("/reports")
➡ List all reports
@app.get("/reports/10")
➡ View report #10
@app.post("/reports")
➡ Generate/Create a new report
@app.put("/reports/10")
➡ Update report #10
@app.delete("/reports/10")
➡ Remove report #10
This pattern is what you'll use most often when building FastAPI applications with routers (APIRouter), SQLAlchemy, and CRUD operations.