File size: 2,201 Bytes
b6f0f70
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
---
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
```bash
pip install -r requirements.txt
```

## Step 1: Init and Setup Project

Run the following commands in your terminal:

```bash
docker-compose up -d
docker-compose down
```

## Step 2: Start PostgreSQL Docker Container
```bash
pip install fastapi[all]
pip install sqlalchemy psycopg2
```

## Step 3: Start FastAPI Server
```bash
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:
```bash
{
    "message": "Hello World!"
}
```
## Step 4: access the PostgreSQL Command Line in the Docker container and create admin role and grant
```bash
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
```bash
docker exec -it <container name> bash
```

Access the running Postgres database with the command:
```bash
psql -U admin <database name>
```

## Step 6: Install uuid-ossp Plugin
Execute the following SQL command to display and install the uuid-ossp extension:
```bash
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:
```bash
pip install alembic
alembic init alembic
```

## Step 8: Create a Revision File for Database Changes
```bash
alembic revision --autogenerate -m "create users table"
```

## Step 9: Apply Database Changes
```bash
alembic upgrade head
```

## Step 10: View Documentation
FastAPI automatically generates API documentation complying with OpenAPI standards.
```bash
Visit http://localhost:8000/docs to explore the API documentation.
```