Setting up a Continuous Integration and Deployment (CI/CD) pipeline for a FastAPI application is a game-changer for any development workflow. It ensures that code changes are automatically validated, tested, and deployed efficiently. This means fewer manual errors, a quicker development cycle, and consistent environments every time.
What’s up with CI/CD?
So, CI/CD, huh? What’s the big deal? CI stands for Continuous Integration. It’s all about regularly dropping your code changes into a shared repository and having them automatically validated through tests. On the flip side, CD is Continuous Deployment. This bad boy automates the deployment of those validated code changes straight to either production or staging environments. Imagine, your application being always good to go - that’s the magic of CI/CD.
FastAPI, Bring It On
Let’s get the ball rolling with a basic FastAPI application. Here’s something super simple to start with:
# main.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
Boom! A FastAPI app with a single endpoint returning a JSON response. Easy peasy.
Docker to the Rescue
Docker rules the containerization game, making sure everything runs smoothly no matter the environment. Here’s the deal on how to integrate Docker into your CI workflow:
-
Dockerfile Magic:
FROM python:3.9-slim WORKDIR /app COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt COPY . . EXPOSE 8000 CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000", "--reload"]
-
Build and Run the Docker Image:
docker build -t my-fastapi-app . docker run -p 8000:8000 my-fastapi-app
Voila! Your FastAPI app is neatly packed in a container, ready to be shipped anywhere.
GitHub Actions for the Win
GitHub Actions is like the Swiss army knife for automating CI/CD pipelines. Here’s how you roll with it:
-
Create a GitHub Actions Workflow File:
name: CI on: push: branches: [ main ] jobs: build-and-test: runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v2 - name: Set up Python 3.9 uses: actions/setup-python@v2 with: python-version: '3.9' - name: Install dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt - name: Run tests run: | python -m pytest tests/ - name: Build Docker image run: | docker build -t my-fastapi-app . - name: Push Docker image to registry uses: docker/build-push-action@v2 with: context: . push: true tags: ${{ secrets.DOCKER_USERNAME }}/my-fastapi-app:latest
-
Store Docker Credentials:
- Store your Docker username and password as secrets in your GitHub repository settings.
It’s Deployment Time
For getting your application live, services like AWS, Google Cloud, or Azure work wonders. Here’s a quick how-to with AWS:
-
Deploy to AWS Elastic Beanstalk:
name: CD on: push: branches: [ main ] jobs: deploy: runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v2 - name: Configure AWS credentials uses: aws-actions/configure-aws-credentials@v1 with: aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }} aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }} aws-region: 'us-east-1' - name: Deploy to Elastic Beanstalk run: | eb init -r us-east-1 -p docker my-fastapi-app eb create my-fastapi-app-env eb deploy my-fastapi-app-env
-
Store AWS Credentials:
- You guessed it! Place your AWS access key and secret key as secrets in your GitHub settings.
Automation with Tests is Key
Automated tests are your sidekicks for ensuring the application’s quality. Here’s how to weave them into your CI pipeline:
-
Write Tests:
# tests/test_main.py from fastapi.testclient import TestClient from main import app client = TestClient(app) def test_read_root(): response = client.get("/") assert response.status_code == 200 assert response.json() == {"Hello": "World"}
-
Run Tests in CI Pipeline:
- name: Run tests run: | python -m pytest tests/
Pre-Commit Hooks – The Unsung Heroes
Pre-commit hooks are lifesavers, making sure you don’t commit code issues. Here’s how:
-
Install Pre-Commit:
pip install pre-commit
-
Configure Pre-Commit Hooks:
repos: - repo: local hooks: - id: trailing-whitespace - id: end-of-file-fixer - id: check-executables-have-shebangs - id: check-added-large-files - id: flake8 - id: black
-
Initialize Pre-Commit:
pre-commit install
The Wrap Up
Setting up a CI/CD pipeline for a FastAPI application is no easy feat, but boy, is it worth it! From integrating Docker for smooth sailing across environments, to automating tests and deployments with GitHub Actions – each step is a piece of a bigger puzzle ensuring your app is always deployment ready.
This whole setup not only clips manual errors but also fast-tracks the development cycle allowing quality features to hit the ground running faster. Whether you’re deploying on AWS, Google Cloud, or whatever cloud, the principles remain as solid as a rock – automate builds, tests, and deployments to keep the consistency and reliability game strong.