Deploying a FastAPI Book Management API on AWS EC2 with Nginx

Introduction In this blog post, I'll walk you through the entire process of building a FastAPI Book Management API and deploying it on an AWS EC2 instance with Nginx as a reverse proxy. This guide is perfect for anyone looking to deploy a backend service in a cloud environment. Setting Up the Project First, let's create and set up our FastAPI application. Step 1: Install FastAPI and Uvicorn pip install fastapi uvicorn Step 2: Create the Project Structure mkdir fastapi-book-project && cd fastapi-book-project mkdir api core tests Step 3: Define the Book Model and In-Memory Database Create a schemas.py file inside api/db/ to define the book schema using Pydantic: from pydantic import BaseModel from enum import Enum from typing import Optional class Genre(str, Enum): fiction = "Fiction" nonfiction = "Non-Fiction" mystery = "Mystery" fantasy = "Fantasy" horror = "Horror" class Book(BaseModel): id: int title: "str" author: str publication_year: int genre: Genre Step 4: Create API Routes Create books.py inside api/routes/: from fastapi import APIRouter, HTTPException from api.db.schemas import Book, Genre router = APIRouter() books_db = [] @router.get("/books", response_model=list[Book]) def get_books(): return books_db @router.post("/books", response_model=Book) def add_book(book: Book): books_db.append(book) return book Step 5: Create the Main App Entry Point In main.py, set up the FastAPI app: from fastapi import FastAPI from api.routes import books app = FastAPI() app.include_router(books.router, prefix="/api/v1") @app.get("/healthcheck") def health_check(): return {"status": "healthy"} Step 6: Run the Application Locally uvicorn main:app --reload Now, visit http://127.0.0.1:8000/docs to test the API. Setting Up an AWS EC2 Instance Step 1: Launch an EC2 Instance Log in to AWS and navigate to EC2. Click Launch Instance. Select Ubuntu 22.04. Choose an instance type (e.g., t2.micro for free-tier users). Configure the security group to allow inbound traffic on ports 22 (SSH) and 80 (HTTP). Launch and download the .pem key file. Step 2: Connect to the EC2 Instance ssh -i your-key.pem ubuntu@your-ec2-public-ip Step 3: Install Required Packages sudo apt update sudo apt install -y python3-pip python3-venv nginx Deploying FastAPI on EC2 Step 1: Clone the Repository git clone https://github.com/hng12-devbotops/fastapi-book-project.git cd fastapi-book-project Step 2: Set Up the Virtual Environment python3 -m venv venv source venv/bin/activate pip install -r requirements.txt Step 3: Run the FastAPI App uvicorn main:app --host 0.0.0.0 --port 8000 & Setting Up Nginx as a Reverse Proxy Step 1: Create a New Nginx Configuration sudo nano /etc/nginx/sites-available/fastapi Add the following content: server { listen 80; server_name your-ec2-public-ip; location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } Step 2: Enable the Configuration sudo ln -s /etc/nginx/sites-available/fastapi /etc/nginx/sites-enabled sudo systemctl restart nginx Step 3: Adjust Firewall Settings sudo ufw allow 'Nginx Full' sudo ufw enable Setting Up CI/CD with GitHub Actions Step 1: Create Github Actions Workflow CI: Run Tests Create a .github/workflows/test.yml file in your repository: name: Run Tests on: pull_request: branches: - main jobs: test: runs-on: ubuntu-latest steps: - name: Checkout Repository uses: actions/checkout@v2 - name: Set up Python uses: actions/setup-python@v4 with: python-version: '3.9' - name: Install Dependencies run: | pip install -r requirements.txt pip install pytest - name: Run Pytest run: pytest CD: Deploy to AWS EC2 Create a .github/workflows/deploy.yml file in your repository: name: Deploy to AWS EC2 on: push: branches: - main jobs: deploy: runs-on: ubuntu-latest steps: - name: Checkout Repository uses: actions/checkout@v2 - name: Deploy to EC2 uses: appleboy/ssh-action@v0.1.3 with: host: ${{ secrets.EC2_HOST }} username: ubuntu key: ${{ secrets.EC2_SSH_KEY }} script: | cd fastapi-book-project git pull origin main source venv/bin/activate pip install -r requirements.txt sudo systemctl res

Feb 15, 2025 - 12:09
 0
Deploying a FastAPI Book Management API on AWS EC2 with Nginx

Introduction

In this blog post, I'll walk you through the entire process of building a FastAPI Book Management API and deploying it on an AWS EC2 instance with Nginx as a reverse proxy. This guide is perfect for anyone looking to deploy a backend service in a cloud environment.

Setting Up the Project

First, let's create and set up our FastAPI application.

Step 1: Install FastAPI and Uvicorn

pip install fastapi uvicorn

Step 2: Create the Project Structure

mkdir fastapi-book-project && cd fastapi-book-project
mkdir api core tests

Step 3: Define the Book Model and In-Memory Database

Create a schemas.py file inside api/db/ to define the book schema using Pydantic:

from pydantic import BaseModel
from enum import Enum
from typing import Optional

class Genre(str, Enum):
    fiction = "Fiction"
    nonfiction = "Non-Fiction"
    mystery = "Mystery"
    fantasy = "Fantasy"
    horror = "Horror"

class Book(BaseModel):
    id: int
    title: "str"
    author: str
    publication_year: int
    genre: Genre

Step 4: Create API Routes

Create books.py inside api/routes/:

from fastapi import APIRouter, HTTPException
from api.db.schemas import Book, Genre

router = APIRouter()
books_db = []

@router.get("/books", response_model=list[Book])
def get_books():
    return books_db

@router.post("/books", response_model=Book)
def add_book(book: Book):
    books_db.append(book)
    return book

Step 5: Create the Main App Entry Point

In main.py, set up the FastAPI app:

from fastapi import FastAPI
from api.routes import books

app = FastAPI()
app.include_router(books.router, prefix="/api/v1")

@app.get("/healthcheck")
def health_check():
    return {"status": "healthy"}

Step 6: Run the Application Locally

uvicorn main:app --reload

Now, visit http://127.0.0.1:8000/docs to test the API.

Setting Up an AWS EC2 Instance

Step 1: Launch an EC2 Instance

  • Log in to AWS and navigate to EC2.
  • Click Launch Instance.
  • Select Ubuntu 22.04.
  • Choose an instance type (e.g., t2.micro for free-tier users).
  • Configure the security group to allow inbound traffic on ports 22 (SSH) and 80 (HTTP).
  • Launch and download the .pem key file.

Step 2: Connect to the EC2 Instance

ssh -i your-key.pem ubuntu@your-ec2-public-ip

Step 3: Install Required Packages

sudo apt update
sudo apt install -y python3-pip python3-venv nginx

Deploying FastAPI on EC2

Step 1: Clone the Repository

git clone https://github.com/hng12-devbotops/fastapi-book-project.git
cd fastapi-book-project

Step 2: Set Up the Virtual Environment

python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt

Step 3: Run the FastAPI App

uvicorn main:app --host 0.0.0.0 --port 8000 &

Setting Up Nginx as a Reverse Proxy

Step 1: Create a New Nginx Configuration

sudo nano /etc/nginx/sites-available/fastapi

Add the following content:

server {
    listen 80;
    server_name your-ec2-public-ip;

    location / {
        proxy_pass http://127.0.0.1:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

Step 2: Enable the Configuration

sudo ln -s /etc/nginx/sites-available/fastapi /etc/nginx/sites-enabled
sudo systemctl restart nginx

Step 3: Adjust Firewall Settings

sudo ufw allow 'Nginx Full'
sudo ufw enable

Setting Up CI/CD with GitHub Actions

Step 1: Create Github Actions Workflow

CI: Run Tests

Create a .github/workflows/test.yml file in your repository:

name: Run Tests

on:
  pull_request:
    branches:
      - main

jobs:
  test:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout Repository
        uses: actions/checkout@v2

      - name: Set up Python
        uses: actions/setup-python@v4
        with:
          python-version: '3.9'

      - name: Install Dependencies
        run: |
          pip install -r requirements.txt
          pip install pytest

      - name: Run Pytest
        run: pytest

CD: Deploy to AWS EC2

Create a .github/workflows/deploy.yml file in your repository:

name: Deploy to AWS EC2

on:
  push:
    branches:
      - main

jobs:
  deploy:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout Repository
        uses: actions/checkout@v2

      - name: Deploy to EC2
        uses: appleboy/ssh-action@v0.1.3
        with:
          host: ${{ secrets.EC2_HOST }}
          username: ubuntu
          key: ${{ secrets.EC2_SSH_KEY }}
          script: |
            cd fastapi-book-project
            git pull origin main
            source venv/bin/activate
            pip install -r requirements.txt
            sudo systemctl restart nginx

Step 2: Add GitHub Secrets

In your repository settings, add:

  • EC2_HOST: Your EC2 Public IP

  • EC2_SSH_KEY: Your private SSH key content

Now, every push to main will automatically deploy your application.

Accessing the API

Now, visit:

http://your-ec2-public-ip/docs

You should see the Swagger UI for testing the API.

Conclusion

In this blog, we successfully built and deployed a FastAPI Book Management API on AWS EC2 using Nginx as a reverse proxy.