A comprehensive FastAPI backend server demonstration showcasing various types of APIs, authentication, file uploads, and best practices.
- 🔐 JWT Authentication - Secure token-based authentication
- 👥 User Management - Complete CRUD operations for users
- 📦 Product Management - Product catalog with search and filtering
- 📁 File Upload - Single and multiple file upload capabilities
- 🔍 Search & Filtering - Advanced search and filtering options
- 📚 API Documentation - Auto-generated Swagger/OpenAPI docs
- 🛡️ Role-based Access Control - Admin and user roles
- 🌐 CORS Support - Cross-origin resource sharing
- ✅ Input Validation - Pydantic models for data validation
- 🏗️ Clean Architecture - Well-organized folder structure
FastAPIServer/
├── app/
│ ├── api/ # API endpoints
│ │ ├── auth.py # Authentication endpoints
│ │ ├── users.py # User management endpoints
│ │ ├── products.py # Product management endpoints
│ │ ├── files.py # File upload endpoints
│ │ └── misc.py # Miscellaneous endpoints
│ ├── core/ # Core functionality
│ │ ├── config.py # Application configuration
│ │ └── security.py # Security utilities
│ ├── models/ # Pydantic models
│ │ └── __init__.py # Data models and schemas
│ └── services/ # Business logic
│ ├── user_service.py # User business logic
│ └── product_service.py # Product business logic
├── tests/ # Test files
├── uploads/ # File upload directory
├── main.py # Application entry point
├── pyproject.toml # Project configuration
└── README.md # This file
-
Clone the repository:
git clone <repository-url> cd FastAPIServer
-
Install dependencies:
pip install -e .
Or install with development dependencies:
pip install -e ".[dev]"
python main.py
uvicorn main:app --host 0.0.0.0 --port 8000
The server will be available at:
- API: http://localhost:8000
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
Method | Endpoint | Description | Auth Required |
---|---|---|---|
POST | /token |
Login to get access token | No |
POST | /register |
Register new user | No |
GET | /me |
Get current user info | Yes |
Example - Login:
curl -X POST "http://localhost:8000/api/v1/auth/token" \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "username=admin&password=admin123"
Example - Register:
curl -X POST "http://localhost:8000/api/v1/auth/register" \
-H "Content-Type: application/json" \
-d '{
"username": "newuser",
"email": "user@example.com",
"password": "password123",
"full_name": "New User"
}'
Method | Endpoint | Description | Auth Required | Admin Only |
---|---|---|---|---|
GET | / |
List all users | Yes | No |
GET | /{user_id} |
Get user by ID | Yes | No |
POST | / |
Create new user | Yes | Yes |
PUT | /{user_id} |
Update user | Yes | Self/Admin |
DELETE | /{user_id} |
Delete user | Yes | Yes |
Example - Get all users:
curl -X GET "http://localhost:8000/api/v1/users/" \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN"
Method | Endpoint | Description | Auth Required | Admin Only |
---|---|---|---|---|
GET | / |
List products | No | No |
GET | /search?q=term |
Search products | No | No |
GET | /{product_id} |
Get product by ID | No | No |
POST | / |
Create product | Yes | Yes |
PUT | /{product_id} |
Update product | Yes | Yes |
DELETE | /{product_id} |
Delete product | Yes | Yes |
Query Parameters for GET /
:
skip
: Number of items to skip (pagination)limit
: Number of items to return (max 100)category
: Filter by category (electronics, clothing, books, home, sports)in_stock
: Filter by stock status (true/false)
Example - Get products:
curl -X GET "http://localhost:8000/api/v1/products/?category=electronics&in_stock=true"
Example - Search products:
curl -X GET "http://localhost:8000/api/v1/products/search?q=macbook"
Method | Endpoint | Description | Auth Required |
---|---|---|---|
POST | /single |
Upload single file | Yes |
POST | /multiple |
Upload multiple files | Yes |
GET | /info |
Get upload constraints | No |
Supported File Types: jpg, jpeg, png, gif, pdf, txt, docx, xlsx Maximum File Size: 10MB Maximum Files per Request: 5 files
Example - Upload single file:
curl -X POST "http://localhost:8000/api/v1/upload/single" \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
-F "file=@/path/to/your/file.pdf"
Method | Endpoint | Description |
---|---|---|
GET | /health |
Health check |
GET | /ping |
Simple ping test |
GET | /time |
Get server time |
GET | /echo?message=hello |
Echo message |
POST | /echo |
Echo JSON data |
GET | /random-quote |
Get random quote |
GET | /weather?city=London |
Get weather (mock data) |
GET | /slow?delay=5 |
Slow endpoint (testing) |
GET | /error?status_code=404 |
Trigger error (testing) |
The application creates default users for testing:
Username | Password | Role | |
---|---|---|---|
admin | admin123 | admin | admin@example.com |
john_doe | user123 | user | john@example.com |
- Register a new user or use default credentials
- Login to get an access token:
POST /api/v1/auth/token { "username": "admin", "password": "admin123" }
- Use the token in subsequent requests:
Authorization: Bearer YOUR_ACCESS_TOKEN
{
"id": 1,
"username": "john_doe",
"email": "john@example.com",
"full_name": "John Doe",
"role": "user",
"is_active": true,
"created_at": "2024-01-01T00:00:00",
"updated_at": null
}
{
"id": 1,
"name": "MacBook Pro",
"description": "Apple MacBook Pro 16-inch with M2 chip",
"price": 2499.99,
"category": "electronics",
"in_stock": true,
"stock_quantity": 10,
"created_at": "2024-01-01T00:00:00",
"updated_at": null
}
The API uses standard HTTP status codes:
200
- Success201
- Created400
- Bad Request401
- Unauthorized403
- Forbidden404
- Not Found422
- Validation Error500
- Internal Server Error
Error responses follow this format:
{
"detail": "Error message description"
}
pytest
black app/ tests/
flake8 app/ tests/
The application can be configured using environment variables or a .env
file:
# Application settings
APP_NAME=FastAPI Demo Server
DEBUG=true
# Security
SECRET_KEY=your-super-secret-key-change-this-in-production
ACCESS_TOKEN_EXPIRE_MINUTES=30
# CORS
ALLOWED_ORIGINS=http://localhost:3000,http://localhost:8080
For production deployment:
- Set
DEBUG=false
- Use a strong
SECRET_KEY
- Configure proper CORS origins
- Use a production WSGI server like Gunicorn
- Set up a reverse proxy (nginx)
- Use a proper database instead of in-memory storage
- Implement proper logging and monitoring
FROM python:3.12-slim
WORKDIR /app
COPY . /app
RUN pip install -e .
EXPOSE 8000
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
# 1. Health check
curl http://localhost:8000/api/v1/misc/health
# 2. Login to get token
TOKEN=$(curl -X POST "http://localhost:8000/api/v1/auth/token" \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "username=admin&password=admin123" | jq -r .access_token)
# 3. Get current user info
curl -H "Authorization: Bearer $TOKEN" \
http://localhost:8000/api/v1/auth/me
# 4. List products
curl http://localhost:8000/api/v1/products/
# 5. Create a new product (admin only)
curl -X POST "http://localhost:8000/api/v1/products/" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"name": "New Product",
"description": "A great product",
"price": 99.99,
"category": "electronics",
"stock_quantity": 5
}'
# 6. Upload a file
curl -X POST "http://localhost:8000/api/v1/upload/single" \
-H "Authorization: Bearer $TOKEN" \
-F "file=@README.md"
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests
- Run tests and linting
- Submit a pull request
This project is for demonstration purposes. Feel free to use it as a starting point for your FastAPI projects.
For questions or issues, please create an issue in the repository or refer to the FastAPI documentation.