Skip to content

Training project for building RESTful APIs with FastAPI - includes authentication, database migrations, Docker containerization, testing, and GitHub Actions CI/CD.

Notifications You must be signed in to change notification settings

osanto/fast-api-example

Repository files navigation

FastAPI Example Project

Tests Deployment Code style: black Python Version FastAPI PostgreSQL

This is an example/template project demonstrating FastAPI best practices for building RESTful APIs with Python, featuring database integration, migrations, containerization, and comprehensive testing.

πŸ“‘ Table of Contents

πŸš€ Features

  • 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)

πŸ“‹ Technology Stack

Core Framework

  • FastAPI - Modern, fast Python web framework for building APIs
  • Python 3.x - Primary programming language

Database & ORM

Testing

DevOps

  • GitHub Actions - CI/CD automation

πŸ“ Project Structure

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

πŸ› οΈ Installation & Setup

Prerequisites

  • Python 3.12+
  • PostgreSQL 12+
  • Docker & Docker Compose (optional, for containerized setup)

Local Development Setup

  1. Clone the repository

    git clone https://github.com/osanto/fast-api-example.git
    cd fast-api-example
  2. Create a virtual environment

    python -m venv venv
    source venv/bin/activate  # On Windows: venv\Scripts\activate
  3. Install dependencies

    pip install -r requirements.txt
    pip install -r requirements-dev.txt  # For development
  4. Set up environment variables

    cp .env.local.example .env.local
    # Edit .env.local with your database credentials and configuration
  5. Run database migrations

    alembic upgrade head
  6. Start the development server

    uvicorn app.main:app --reload
  7. Access the application

Docker Setup (Alternative)

  1. Set up environment variables for Docker

    cp .env.docker.example .env.docker
    # Edit .env.docker with your configuration
  2. Start services with Docker Compose

    docker-compose up -d

    This will start:

    • PostgreSQL database
    • FastAPI application with auto-reload
    • Automatic database migrations
  3. Access the application

  4. Stop services

    docker-compose down

πŸ§ͺ Testing

Run All Tests

pytest

Run Tests with Coverage

pytest --cov=app --cov-report=html

Run Specific Test File

pytest tests/tests_integration/test_posts.py

πŸ“Š How to Use the API

This is a social media-style API where users can create posts, and other users can vote on them.

Quick Start Guide

  1. Register a User β†’ Create an account
  2. Login β†’ Get authentication token
  3. Create Posts β†’ Share content
  4. Vote on Posts β†’ Like/upvote posts from other users
  5. View Posts β†’ See all posts with vote counts

swagger view

API Endpoints Reference

❀️ Health Check

Check Application Health
GET /

Response:

{
  "status": "healthy",
  "message": "FastAPI is running"
}

Used by deployment platforms (like Render) to verify the application is running correctly.


πŸ” Authentication & Users

Register a New User
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"
}
Login
POST /auth/login
Content-Type: application/x-www-form-urlencoded

username=user@example.com&password=securepassword123

Response:

{
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "token_type": "bearer"
}

Note: Use this token in the Authorization header for authenticated requests:

Authorization: Bearer <your_access_token>
Get User Details
GET /users/{id}

Response:

{
  "id": 1,
  "email": "user@example.com",
  "created_at": "2024-01-01T12:00:00Z"
}

πŸ“ Posts

Get All Posts
GET /posts

Optional 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=python

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
  }
]
Get a Specific Post
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
}
Create a New Post
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
}
Update a Post
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 a Post
DELETE /posts/{id}
Authorization: Bearer <token>

Response: 204 No Content

Note: You can only delete your own posts.


πŸ‘ Votes

Vote on a Post
POST /votes
Authorization: Bearer <token>
Content-Type: application/json

{
  "post_id": 1,
  "dir": 1
}

Parameters:

  • post_id - ID of the post to vote on
  • dir - Vote direction: 1 for upvote, 0 for no vote

Response:

{
  "message": "Successfully added vote"
}

Note: You cannot vote on your own posts.

Remove a Vote
DELETE /votes
Authorization: Bearer <token>
Content-Type: application/json

{
  "post_id": 1
}

Response:

{
  "message": "Successfully deleted vote"
}

πŸ“– Interactive API Documentation

For a complete, interactive API documentation with the ability to test endpoints directly:

These provide:

  • Full request/response schemas
  • Try-it-out functionality
  • Authentication testing
  • Example requests and responses

πŸ—„οΈ Database Migrations

Create a New Migration

alembic revision --autogenerate -m "Description of changes"

Apply Migrations

alembic upgrade head

Rollback Migration

alembic downgrade -1

View Migration History

alembic history

πŸ”§ Development

Code Quality Tools

The project uses the following tools (configured in requirements-dev.txt):

  • Black - Code formatting
  • Flake8 - Linting

Running Linters

# Format code
black app/ tests/

# Check linting
flake8 app/ tests/

βš™οΈ CI/CD with GitHub Actions

This project uses GitHub Actions for continuous integration and deployment. The workflow is defined in .github/workflows/build-deploy.yml.

Workflow: Test and Deploy

Triggers:

  • Push to any branch
  • Pull requests to any branch

Jobs:

1. Build & Test Job

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)

2. Deploy Job (Production)

  • Deploy to Render
    • Runs only on pushes to main branch after tests pass

Required GitHub Secrets

Secret Name Description
RENDER_DEPLOY_HOOK Render deploy hook URL for automatic deployment

πŸš€ Deployment

Current 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

Deployment Steps

The automated deployment process on Render:

  1. Code Push β†’ Developer pushes to main branch
  2. GitHub Actions β†’ Runs tests and validates code
  3. Render Detection β†’ Render detects new commit
  4. Build β†’ Render installs Python dependencies from requirements.txt
  5. Database Migration β†’ Alembic runs migrations automatically
  6. Deploy β†’ New version is deployed with zero downtime
  7. Health Check β†’ Render verifies application is responding
  8. Live β†’ New version is live at production URL - https://fast-api-example-w11a.onrender.com/docs
  9. Rollback β†’ Previous version kept for instant rollback if needed

πŸ“„ License

This project is open source and available under the MIT License.

πŸ™ Acknowledgments

About

Training project for building RESTful APIs with FastAPI - includes authentication, database migrations, Docker containerization, testing, and GitHub Actions CI/CD.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published