This is an example/template project demonstrating FastAPI best practices for building RESTful APIs with Python, featuring database integration, migrations, containerization, and comprehensive testing.
- Features
- Technology Stack
- Project Structure
- Installation & Setup
- Testing
- How to Use the API
- Database Migrations
- Development
- CI/CD with GitHub Actions
- Deployment
- License
- Acknowledgments
- Modern Python API Framework - Built with FastAPI for high performance and automatic API documentation
- Database Integration - PostgreSQL with SQLAlchemy ORM for data management
- Database Migrations - Alembic for version-controlled schema changes
- Containerization - Docker and Docker Compose
- Testing - Integration tests using pytest and FastAPI TestClient
- CI/CD Pipeline - GitHub Actions for automated testing and deployment
- API Documentation - Auto-generated interactive API docs (Swagger/OpenAPI)
- FastAPI - Modern, fast Python web framework for building APIs
- Python 3.x - Primary programming language
- PostgreSQL - Relational database
- SQLAlchemy - Python SQL toolkit and ORM
- Alembic - Database migration tool
- pytest - Testing framework
- FastAPI TestClient - Built-in testing utilities
- GitHub Actions - CI/CD automation
fast-api-example/
βββ .github/
β βββ workflows/ # GitHub Actions CI/CD pipelines
βββ alembic/ # Database migration scripts
β βββ versions/ # Migration version files
βββ app/ # Main application code
β βββ routers/ # API route handlers
β β βββ auth.py # Authentication routes
β β βββ post.py # Post routes
β β βββ user.py # User routes
β β βββ vote.py # Vote routes
β βββ config.py # Configuration management
β βββ database.py # Database configuration
β βββ main.py # FastAPI application entry point
β βββ models.py # SQLAlchemy models
β βββ oauth2.py # OAuth2/JWT authentication
β βββ schemas.py # Pydantic schemas
β βββ utils.py # Utility functions
βββ tests/
β βββ tests_integration/ # Integration tests
β βββ conftest.py # Pytest fixtures and configuration
β βββ test_posts.py # Posts API tests
β βββ test_users.py # Users API tests
β βββ test_votes.py # Votes API tests
βββ .env.docker.example # Docker environment variables template
βββ .env.local.example # Local development environment template
βββ alembic.ini # Alembic configuration
βββ docker-compose.yml # Docker Compose configuration
βββ Dockerfile # Docker image definition
βββ requirements.txt # Production dependencies
βββ requirements-dev.txt # Development dependencies
- Python 3.12+
- PostgreSQL 12+
- Docker & Docker Compose (optional, for containerized setup)
-
Clone the repository
git clone https://github.com/osanto/fast-api-example.git cd fast-api-example -
Create a virtual environment
python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate
-
Install dependencies
pip install -r requirements.txt pip install -r requirements-dev.txt # For development -
Set up environment variables
cp .env.local.example .env.local # Edit .env.local with your database credentials and configuration -
Run database migrations
alembic upgrade head
-
Start the development server
uvicorn app.main:app --reload
-
Access the application
- API: http://localhost:8000
- Interactive API docs (Swagger): http://localhost:8000/docs
- Alternative API docs (ReDoc): http://localhost:8000/redoc
-
Set up environment variables for Docker
cp .env.docker.example .env.docker # Edit .env.docker with your configuration -
Start services with Docker Compose
docker-compose up -d
This will start:
- PostgreSQL database
- FastAPI application with auto-reload
- Automatic database migrations
-
Access the application
- API: http://localhost:8000
- Interactive API docs: http://localhost:8000/docs
-
Stop services
docker-compose down
pytestpytest --cov=app --cov-report=htmlpytest tests/tests_integration/test_posts.pyThis is a social media-style API where users can create posts, and other users can vote on them.
- Register a User β Create an account
- Login β Get authentication token
- Create Posts β Share content
- Vote on Posts β Like/upvote posts from other users
- View Posts β See all posts with vote counts
GET /Response:
{
"status": "healthy",
"message": "FastAPI is running"
}Used by deployment platforms (like Render) to verify the application is running correctly.
POST /users
Content-Type: application/json
{
"email": "user@example.com",
"password": "securepassword123"
}Response:
{
"id": 1,
"email": "user@example.com",
"created_at": "2024-01-01T12:00:00Z"
}POST /auth/login
Content-Type: application/x-www-form-urlencoded
username=user@example.com&password=securepassword123Response:
{
"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"token_type": "bearer"
}Note: Use this token in the Authorization header for authenticated requests:
Authorization: Bearer <your_access_token>
GET /users/{id}Response:
{
"id": 1,
"email": "user@example.com",
"created_at": "2024-01-01T12:00:00Z"
}GET /postsOptional Query Parameters:
limit- Number of posts to return (default: 10)skip- Number of posts to skip (pagination)search- Search posts by title/content
Example:
GET /posts?limit=5&skip=0&search=pythonResponse:
[
{
"id": 1,
"title": "My First Post",
"content": "Hello World!",
"published": true,
"created_at": "2024-01-01T12:00:00Z",
"owner_id": 1,
"owner": {
"id": 1,
"email": "user@example.com"
},
"votes": 5
}
]GET /posts/{id}Response:
{
"id": 1,
"title": "My First Post",
"content": "Hello World!",
"published": true,
"created_at": "2024-01-01T12:00:00Z",
"owner_id": 1,
"owner": {
"id": 1,
"email": "user@example.com"
},
"votes": 5
}POST /posts
Authorization: Bearer <token>
Content-Type: application/json
{
"title": "My Awesome Post",
"content": "This is the content of my post",
"published": true
}Response:
{
"id": 2,
"title": "My Awesome Post",
"content": "This is the content of my post",
"published": true,
"created_at": "2024-01-01T13:00:00Z",
"owner_id": 1
}PUT /posts/{id}
Authorization: Bearer <token>
Content-Type: application/json
{
"title": "Updated Title",
"content": "Updated content",
"published": true
}Note: You can only update your own posts.
DELETE /posts/{id}
Authorization: Bearer <token>Response: 204 No Content
Note: You can only delete your own posts.
POST /votes
Authorization: Bearer <token>
Content-Type: application/json
{
"post_id": 1,
"dir": 1
}Parameters:
post_id- ID of the post to vote ondir- Vote direction:1for upvote,0for no vote
Response:
{
"message": "Successfully added vote"
}Note: You cannot vote on your own posts.
DELETE /votes
Authorization: Bearer <token>
Content-Type: application/json
{
"post_id": 1
}Response:
{
"message": "Successfully deleted vote"
}For a complete, interactive API documentation with the ability to test endpoints directly:
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
These provide:
- Full request/response schemas
- Try-it-out functionality
- Authentication testing
- Example requests and responses
alembic revision --autogenerate -m "Description of changes"alembic upgrade headalembic downgrade -1alembic historyThe project uses the following tools (configured in requirements-dev.txt):
- Black - Code formatting
- Flake8 - Linting
# Format code
black app/ tests/
# Check linting
flake8 app/ tests/This project uses GitHub Actions for continuous integration and deployment. The workflow is defined in .github/workflows/build-deploy.yml.
Triggers:
- Push to any branch
- Pull requests to any branch
Jobs:
Runs on every push and pull request:
-
Setup Environment
- Checkout code
- Set up Python 3.12
- Install dependencies
-
Database Setup
- Start PostgreSQL service container
- Run database migrations with Alembic
-
Run Tests
- Execute pytest test suite
- Generate test coverage reports
- Ensure all integration tests pass
-
Code Quality Checks
- Run linting (Flake8)
- Check code formatting (Black)
- Deploy to Render
- Runs only on pushes to
mainbranch after tests pass
- Runs only on pushes to
| Secret Name | Description |
|---|---|
RENDER_DEPLOY_HOOK |
Render deploy hook URL for automatic deployment |
This project is deployed to Render - a modern cloud platform that automatically builds and deploys from GitHub.
Deployment Platform: Render.com
Deployment Method: Automatic from GitHub
Deployment Trigger: Automatic on push to main branch
Database: Managed PostgreSQL on Render
The automated deployment process on Render:
- Code Push β Developer pushes to
mainbranch - GitHub Actions β Runs tests and validates code
- Render Detection β Render detects new commit
- Build β Render installs Python dependencies from
requirements.txt - Database Migration β Alembic runs migrations automatically
- Deploy β New version is deployed with zero downtime
- Health Check β Render verifies application is responding
- Live β New version is live at production URL - https://fast-api-example-w11a.onrender.com/docs
- Rollback β Previous version kept for instant rollback if needed
This project is open source and available under the MIT License.
