Implement a REST API in Python for creating and reading users. The API should have endpoints for creating a user, reading all users, and reading a single user.
Not applicable
Assistant
Problem: Implement a REST API in Python for creating and reading users. The API should have endpoints for creating a user, reading all users, and reading a single user.
Not applicable
Approach: FastAPI
Let me implement this solution.
Here is a complete implementation of a REST API in Python using FastAPI.
FastAPI is chosen for this implementation because it is modern, high-performance, and allows for automatic validation and documentation (Swagger UI) with minimal code.
Prerequisites
You will need to install FastAPI and Uvicorn (the web server):
bash
pip install fastapi uvicorn
The Code
Save the following code in a file named main.py.
python
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import List, Optional
# 1. Initialize the API
app = FastAPI(title="Simple User API")
# 2. Define Data Models
class UserBase(BaseModel):
name: str
email: str
class User(UserBase):
id: int
# 3. In-Memory Database
# We use a list to store users temporarily.
# Note: Data will be lost when the server restarts.
fake_db: List[User] = []
# 4. Helper function to generate IDs
def generate_id() -> int:
if not fake_db:
return 1
return fake_db[-1].id + 1
# 5. API Endpoints
@app.post("/users/", response_model=User, status_code=201)
def create_user(user: UserBase):
"""
Create a new user.
"""
new_id = generate_id()
# Check if email already exists (simple validation)
for u in fake_db:
if u.email == user.email:
raise HTTPException(status_code=400, detail="Email already registered")
new_user = User(id=new_id, name=user.name, email=user.email)
fake_db.append(new_user)
return new_user
@app.get("/users/", response_model=List[User])
def read_users():
"""
Read all users.
"""
return fake_db
@app.get("/users/{user_id}", response_model=User)
def read_user(user_id: int):
"""
Read a single user by ID.
"""
for user in fake_db:
if user.id == user_id:
return user
# If user not found, raise 404 error
raise HTTPException(status_code=404, detail="User not found")
# Run the application (optional i