Skip to content
/ Fast-Api-example Public template

Simple asynchronous API implemented with Fast-Api framework utilizing Postgres as a Database and SqlAlchemy as ORM . GitHub Actions as CI/CD Pipeline

License

Notifications You must be signed in to change notification settings

KenMwaura1/Fast-Api-example

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

661 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

FastAPI Example App

fastapi-0.115.8 python-3.13 CodeQL Docker Compose Actions Workflow

"Buy Me A Coffee" Twitter

A production-ready asynchronous REST API built with FastAPI, featuring CRUD operations for notes management. The API includes advanced features like search, filtering, pagination, and is fully containerized with Docker.

✨ Features

  • πŸš€ Asynchronous API - Built with FastAPI and async/await patterns
  • 🐘 PostgreSQL Database - Production-grade database with asyncpg driver
  • πŸ” Search & Filter - Unified search with pagination support
  • πŸ“ CRUD Operations - Complete Create, Read, Update, Delete functionality
  • 🐳 Docker Support - Fully containerized with Docker Compose
  • πŸ§ͺ Testing - Comprehensive test suite with pytest
  • πŸ“š API Documentation - Auto-generated OpenAPI/Swagger docs
  • 🎨 Vue Frontend - Optional modern frontend with Vite

Fast-api

πŸ“– Table of Contents

πŸš€ Quick Start with Docker

The fastest way to get started is using Docker Compose:

Prerequisites

Steps

  1. Clone the repository

    git clone https://github.com/KenMwaura1/Fast-Api-example.git
    cd Fast-Api-example
  2. Start the application

    docker-compose up -d --build
  3. Access the API

Note: If you've previously run Docker Compose, reset the database volume: docker-compose down -v && docker-compose up -d --build

πŸ’» Local Installation

Prerequisites

  • Python 3.13+
  • PostgreSQL 12+
  • pip or uv package manager

Setup Instructions

  1. Clone the repository

    git clone https://github.com/KenMwaura1/Fast-Api-example.git
    cd Fast-Api-example
  2. Create and activate virtual environment

    python3 -m venv venv
    
    # Linux/Mac
    source venv/bin/activate
    
    # Windows
    .\venv\Scripts\activate
  3. Install dependencies

    cd src
    pip install -r requirements.txt
  4. Configure database

    Create a PostgreSQL database:

    CREATE DATABASE fast_api_dev;
    CREATE USER hello_fastapi WITH PASSWORD 'your_password';
    GRANT ALL PRIVILEGES ON DATABASE fast_api_dev TO hello_fastapi;

    Or update the DATABASE_URL in src/app/.env:

    DATABASE_URL=postgresql://user:password@localhost/dbname
  5. Run the application

    cd ..
    ./run.sh
  6. Access the API

🎨 Vue Frontend (Optional)

A modern Vue 3 frontend built with Vite is included for testing the API.

Prerequisites

  • Node.js 16+ or 18+ (LTS recommended)
  • npm or yarn

Setup

  1. Navigate to frontend directory

    cd vue-client
  2. Install dependencies

    npm install
    # or
    yarn install
  3. Start development server

    npm run dev
    # or
    yarn dev
  4. Access the frontend

The frontend displays notes with their completion status and formatted creation dates.

πŸ“‘ API Endpoints

Notes

Method Endpoint Description Query Parameters
GET /notes List all notes skip, limit, search, completed
POST /notes Create a note -
GET /notes/{id} Get a note -
PUT /notes/{id} Update a note -
DELETE /notes/{id} Delete a note -

Ping

Method Endpoint Description
GET /ping Health check

Example Request

# Get all completed notes with pagination
curl "http://localhost:8002/notes?completed=true&skip=0&limit=10"

# Search notes
curl "http://localhost:8002/notes?search=fastapi"

## πŸ§ͺ Testing

The project includes a comprehensive test suite using pytest with database mocking.

### Run Tests

```bash
# From the project root
export PYTHONPATH=$PYTHONPATH:$(pwd)/src
./venv/bin/python -m pytest src

# With coverage
./venv/bin/python -m pytest src --cov=src --cov-report=html

# Run specific test file
./venv/bin/python -m pytest src/tests/test_notes.py

Test Structure

  • tests/test_ping.py - Health check endpoint tests
  • tests/test_notes.py - CRUD operations and filtering tests
  • tests/conftest.py - Shared fixtures and test configuration

πŸ“š Documentation

API Documentation

Tech Stack

  • Framework: FastAPI 0.115.8
  • Python: 3.13
  • Database: PostgreSQL with asyncpg
  • ORM: SQLAlchemy 1.4.50
  • Server: Uvicorn with uvloop
  • Testing: pytest 7.4.3
  • Frontend: Vue 3 + Vite

πŸ› οΈ Development

Project Structure

Fast-Api-example/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ app/
β”‚   β”‚   β”œβ”€β”€ api/          # API routes
β”‚   β”‚   β”‚   β”œβ”€β”€ notes.py  # Notes endpoints
β”‚   β”‚   β”‚   β”œβ”€β”€ ping.py   # Health check
β”‚   β”‚   β”‚   β”œβ”€β”€ crud.py   # Database operations
β”‚   β”‚   β”‚   └── models.py # Pydantic models
β”‚   β”‚   β”œβ”€β”€ db.py         # Database configuration
β”‚   β”‚   └── main.py       # Application entry point
β”‚   β”œβ”€β”€ tests/            # Test suite
β”‚   β”œβ”€β”€ Dockerfile        # Docker configuration
β”‚   └── requirements.txt  # Python dependencies
β”œβ”€β”€ vue-client/           # Vue frontend
β”œβ”€β”€ docker-compose.yml    # Docker Compose config
└── run.sh               # Local run script

Environment Variables

Create a .env file in src/app/:

DATABASE_URL=postgresql://hello_fastapi:password@localhost/fast_api_dev
ENVIRONMENT=development

🀝 Contributing

Contributions are welcome! Please follow these steps:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Contribution Guidelines

  • Follow PEP 8 style guide
  • Add tests for new features
  • Update documentation as needed
  • Ensure all tests pass before submitting PR

🚒 CI/CD & Deployment

GitHub Actions

The project uses GitHub Actions for CI/CD with two main workflows:

  • CodeQL Analysis - Security scanning and code quality checks
  • Docker Build & Push - Automated Docker image builds

Docker Hub

Pre-built Docker images are available at:

Required Secrets

To use GitHub Actions, add these secrets to your repository:

For Docker Hub:

  • DOCKER_USERNAME - Your Docker Hub username
  • DOCKER_PASSWORD - Your Docker Hub password or access token

For GitHub Packages:

  • CR_PAT - Personal Access Token with write:packages scope
  • CR_USERNAME - Your GitHub username

Note: You can remove or comment out the Docker push steps if you don't need image publishing.

Pull Pre-built Image

docker pull kenmwaura1/fast-api-example:latest

πŸ“– Resources

πŸ› Troubleshooting

Installation Issues

Python Package Installation Fails

If you encounter errors installing packages (especially pydantic-core or greenlet):

  1. Ensure you have Python 3.13 or 3.12 (not 3.14+, which has compatibility issues)

    python --version
  2. Install build dependencies (Linux/Mac):

    # Ubuntu/Debian
    sudo apt-get install build-essential libssl-dev libffi-dev python3-dev
    
    # Mac
    brew install build-essential openssl
  3. Upgrade pip, setuptools, and wheel:

    pip install --upgrade pip setuptools wheel

Database Connection Issues

"Connection refused" when starting the app

  1. Verify PostgreSQL is running:

    # Check status
    sudo systemctl status postgresql
    
    # Start if not running
    sudo systemctl start postgresql
  2. Verify credentials in .env:

    # Check database exists
    psql -U hello_fastapi -d fast_api_dev -c "SELECT 1"
  3. Check database connection string:

    DATABASE_URL=postgresql://username:password@localhost:5432/database_name

Using Docker database

If using Docker Compose:

# Check if database container is running
docker-compose ps

# View database logs
docker-compose logs db

# Restart database
docker-compose restart db

Port Already in Use

Port 8000 or 8002 already in use

# Find process using port 8000
lsof -i :8000

# Kill the process (replace PID with actual process ID)
kill -9 <PID>

# Or use a different port
PORT=8001 ./run.sh

Docker Issues

Docker build fails

  1. Ensure you're using Python 3.13:

    • Check src/Dockerfile line 2
  2. Clear Docker cache:

    docker system prune -a
    docker-compose down -v
  3. Rebuild:

    docker-compose up -d --build

Container exits immediately

# Check container logs
docker-compose logs web

# Or for specific container
docker logs <container_id>

API Issues

404 Not Found on /docs

The API might not be running at the expected URL:

  • Verify the port: Check ./run.sh for PORT setting
  • Verify the host: Usually http://localhost:8000
  • Check that the API actually started without errors

422 Validation Error

Usually means your request data doesn't match expected format:

  • Check field lengths: title (3-255), description (3-1000)
  • Ensure required fields are included
  • Verify JSON format is correct

500 Internal Server Error

Check the application logs:

# For local development
# Errors should show in the terminal where you ran ./run.sh

# For Docker
docker-compose logs web

Testing Issues

Tests fail with "ModuleNotFoundError"

# Set PYTHONPATH correctly
export PYTHONPATH=$PYTHONPATH:$(pwd)/src
pytest src -v

Database-related test failures

Tests use mocked database, so this usually means the test fixture isn't working:

# Check conftest.py exists
cat src/tests/conftest.py

# Run with verbose output
pytest src -v -s

Performance Issues

Slow API responses

  1. Check database performance:

    -- Log in to database
    psql -U hello_fastapi -d fast_api_dev
    
    -- Check table size
    SELECT pg_size_pretty(pg_total_relation_size('notes'));
  2. Check query logs (if enabled)

  3. Verify indexes exist on frequently queried columns

High memory usage

  • Reduce limit parameter in queries (max is 100)
  • Check for memory leaks in custom code
  • Monitor using docker stats (for Docker deployment)

Frontend Issues

Vue frontend can't connect to API

  1. Verify API is running:

    curl http://localhost:8000/ping
  2. Check CORS configuration in .env:

    ALLOWED_ORIGINS=http://localhost:5173,http://localhost
  3. Check frontend URL in browser matches one of allowed origins

Still Having Issues?

  1. Check the documentation:

  2. Search existing issues:

  3. Open a new issue with:

    • Clear description of the problem
    • Steps to reproduce
    • Error messages and logs
    • Environment details (OS, Python version, etc.)
  4. Ask for help:

    • GitHub Discussions
    • Stack Overflow (tag with fastapi, postgresql)

πŸ“ License

This project is licensed under the MIT License.

πŸ‘€ Author

Kennedy Mwaura

β˜• Support

If you find this project helpful, consider:

"Buy Me A Coffee"


Built with ❀️ using FastAPI

About

Simple asynchronous API implemented with Fast-Api framework utilizing Postgres as a Database and SqlAlchemy as ORM . GitHub Actions as CI/CD Pipeline

Topics

Resources

License

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors 3

  •  
  •  
  •