A complete FastAPI backend implementation for a Simple Social Networking Service (SNS) that allows users to create, retrieve, update, and delete posts; add comments; and like/unlike posts.
- Framework: FastAPI with Python 3.12+
- Database: SQLite (
sns_api.db) - API Documentation: Swagger UI + OpenAPI 3.1 specification
- CORS: Enabled for cross-origin requests
- Data Validation: Pydantic models with comprehensive validation
python/
├── main.py # FastAPI application entry point
├── models.py # Pydantic data models and schemas
├── database.py # SQLite database operations
├── openapi.yaml # OpenAPI 3.0.1 specification
├── sns_api.db # SQLite database file (auto-created)
├── README.md # This documentation
└── .venv/ # Virtual environment (created during setup)
Refer to the README doc for preparation.
First, set the environment variable of $REPOSITORY_ROOT.
# bash/zsh
REPOSITORY_ROOT=$(git rev-parse --show-toplevel)# PowerShell
$REPOSITORY_ROOT = git rev-parse --show-toplevelThen, navigate to the python directory and create a virtual environment:
cd $REPOSITORY_ROOT/complete/pythonCreate virtual environment
# Using uv (recommended)
uv venv .venv# Using standard Python (alternative)
python -m venv .venv# On Linux/macOS
source .venv/bin/activate# On Windows Command Prompt
.venv\Scripts\activate# Using uv (recommended)
uv pip install fastapi uvicorn python-multipart pyyaml
```bash
```bash
# Using pip (alternative)
pip install fastapi uvicorn python-multipart pyyamlCopy the OpenAPI spec from parent directory.
# On Linux/macOS
cp ../openapi.yaml .
```bash
```powershell
# On Windows Command Prompt
xcopy ..\openapi.yaml .Start the development server
uvicorn main:app --host 0.0.0.0 --port 8000 --reloadThe application will be available at:
- API Base URL:
http://localhost:8000/api/ - Swagger UI:
http://localhost:8000/docs - OpenAPI Specification:
http://localhost:8000/openapi.json
The application uses SQLite with the following tables:
id(TEXT, PRIMARY KEY) - UUIDusername(TEXT, NOT NULL) - Author usernamecontent(TEXT, NOT NULL) - Post contentcreated_at(TEXT, NOT NULL) - ISO timestampupdated_at(TEXT, NOT NULL) - ISO timestamp
id(TEXT, PRIMARY KEY) - UUIDpost_id(TEXT, NOT NULL) - Foreign key to postsusername(TEXT, NOT NULL) - Author usernamecontent(TEXT, NOT NULL) - Comment contentcreated_at(TEXT, NOT NULL) - ISO timestampupdated_at(TEXT, NOT NULL) - ISO timestamp
post_id(TEXT, NOT NULL) - Foreign key to postsusername(TEXT, NOT NULL) - User who likedliked_at(TEXT, NOT NULL) - ISO timestamp- Primary key:
(post_id, username)
GET /api/posts- List all postsPOST /api/posts- Create a new postGET /api/posts/{postId}- Get a specific postPATCH /api/posts/{postId}- Update a postDELETE /api/posts/{postId}- Delete a post
GET /api/posts/{postId}/comments- List comments for a postPOST /api/posts/{postId}/comments- Create a commentGET /api/posts/{postId}/comments/{commentId}- Get a specific commentPATCH /api/posts/{postId}/comments/{commentId}- Update a commentDELETE /api/posts/{postId}/comments/{commentId}- Delete a comment
POST /api/posts/{postId}/likes- Like a postDELETE /api/posts/{postId}/likes?username={username}- Unlike a post
curl -X POST "http://localhost:8000/api/posts" \
-H "Content-Type: application/json" \
-d '{"username": "john_doe", "content": "Hello World! This is my first post."}'curl -X GET "http://localhost:8000/api/posts"curl -X POST "http://localhost:8000/api/posts/{POST_ID}/comments" \
-H "Content-Type: application/json" \
-d '{"username": "jane_smith", "content": "Great post!"}'curl -X POST "http://localhost:8000/api/posts/{POST_ID}/likes" \
-H "Content-Type: application/json" \
-d '{"username": "alice_johnson"}'- Navigate to
http://localhost:8000/docs - Explore and test all API endpoints interactively
- View request/response schemas and examples
NewPostRequest:{username: str, content: str}UpdatePostRequest:{username: str, content: str}NewCommentRequest:{username: str, content: str}UpdateCommentRequest:{username: str, content: str}LikeRequest:{username: str}
Post: Full post object with metadata and countsComment: Full comment object with metadataLikeResponse: Like confirmation with timestamp
The application uses default settings but can be customized:
- Database: SQLite file
sns_api.db(auto-created) - Host:
0.0.0.0(all interfaces) - Port:
8000 - CORS: Enabled for all origins
For production deployment, consider:
- Database: Switch to PostgreSQL or MySQL
- Environment Variables: Use for sensitive configuration
- Security: Add authentication and authorization
- CORS: Restrict to specific domains
- Logging: Implement structured logging
- Monitoring: Add health checks and metrics
main.py: FastAPI app configuration, middleware, and route definitionsmodels.py: Pydantic models for data validation and serializationdatabase.py: SQLite operations, connection management, and CRUD functions
The project follows:
- Python PEP 8 style guidelines
- FastAPI best practices
- Functional programming patterns
- Type hints throughout
- Comprehensive error handling
- Define Pydantic models in
models.py - Add database operations in
database.py - Create API endpoints in
main.py - Update OpenAPI specification if needed
- Port already in use: Change port with
--port 8001 - Virtual environment issues: Recreate with
rm -rf .venv && uv venv .venv - Database locked: Stop all running instances of the application
- Import errors: Ensure virtual environment is activated
Run with additional logging:
uvicorn main:app --host 0.0.0.0 --port 8000 --reload --log-level debug