tebakaja's picture
migrate: GCP to Hugging Face
a046a2c
metadata
title: Docpet Backend Service
emoji: πŸ‘¨β€βš•οΈ
colorFrom: purple
colorTo: green
sdk: docker
python_version: '3.9'

Backend with FastAPI Docker Setup Guide

This guide walks you through setting up a FastAPI project with PostgreSQL using Docker and integrating Alembic for database migrations.

Prerequisites

  • Docker installed on your machine
  • Python and pip install
pip install -r requirements.txt

Step 1: Init and Setup Project

Run the following commands in your terminal:

docker-compose up -d
docker-compose down

Step 2: Start PostgreSQL Docker Container

pip install fastapi[all]
pip install sqlalchemy psycopg2

Step 3: Start FastAPI Server

uvicorn app.main:app --host localhost --port 8000 --reload

Make a GET request to http://localhost:8000/api/healthchecker in Postman or any API testing tool to verify the response:

{
    "message": "Hello World!"
}

Step 4: access the PostgreSQL Command Line in the Docker container and create admin role and grant

docker exec -it postgres psql -U postgres

CREATE USER admin WITH PASSWORD 'your_password';

GRANT ALL PRIVILEGES ON DATABASE docpet TO admin;

Step 5: Access PostgreSQL Docker Container Shell

docker exec -it <container name> bash

Access the running Postgres database with the command:

psql -U admin <database name>

Step 6: Install uuid-ossp Plugin

Execute the following SQL command to display and install the uuid-ossp extension:

select * from pg_available_extensions;

CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

Step 7: Initialize Alembic for Database Migrations

Execute the following SQL command to display and install the uuid-ossp extension:

pip install alembic
alembic init alembic

Step 8: Create a Revision File for Database Changes

alembic revision --autogenerate -m "create users table"

Step 9: Apply Database Changes

alembic upgrade head

Step 10: View Documentation

FastAPI automatically generates API documentation complying with OpenAPI standards.

Visit http://localhost:8000/docs to explore the API documentation.