CRUD stands for Create, Read, Update, and Delete. These are the basic operations performed on database resources.
In an API, CRUD operations are commonly used to manage resources such as users, products, orders, or posts.
Code
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class User(BaseModel):
name: str
email: str
age: int
users = []
@app.post("/users")
def create_user(user: User):
users.append(user)
return user
@app.get("/users")
def get_users():
return users
@app.put("/users/{user_id}")
def update_user(user_id: int, user: User):
users[user_id] = user
return user
@app.delete("/users/{user_id}")
def delete_user(user_id: int):
users.pop(user_id)
return {
"message": "User deleted"
}
Understanding the Code
Create
The POST endpoint is used to create a new user:
@app.post("/users")
def create_user(user: User):
users.append(user)
return user
The new user is added to the users list.
Read
The GET endpoint is used to retrieve users:
@app.get("/users")
def get_users():
return users
It returns the users currently stored in the list.
Update
The PUT endpoint is used to update an existing user:
@app.put("/users/{user_id}")
def update_user(user_id: int, user: User):
users[user_id] = user
return user
The user_id identifies which user should be updated.
Delete
The DELETE endpoint removes a user:
@app.delete("/users/{user_id}")
def delete_user(user_id: int):
users.pop(user_id)
return {
"message": "User deleted"
}
The user_id identifies which user should be removed.
CRUD Operations
The four basic CRUD operations are:
| Operation | HTTP Method | Endpoint |
|---|---|---|
| Create | POST | /users |
| Read | GET | /users |
| Update | PUT | /users/{id} |
| Delete | DELETE | /users/{id} |
Summary
CRUD provides the basic operations required to manage resources:
POST /users → Create
GET /users → Read
PUT /users/{id} → Update
DELETE /users/{id} → Delete
In this example, the data is stored in a Python list. In a real FastAPI application, these operations would typically work with a database.