Continuous Integration (CI) is a software development practice that involves automatically building, testing, and deploying code changes. GitHub Actions provides a powerful platform for implementing CI workflows. In this guide, we’ll demonstrate how to set up CI for a FastAPI application using GitHub Actions.
Creating a GitHub Actions Workflow
Create a .github/workflows/ci.yml
file in your project’s root directory.
Define the workflow:
YAML
name: CI
on:
push:
branches: [main]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Set up Python environment
uses: actions/setup-python@v4
with:
python-version: '3.10'
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements.txt
- name: Run tests
run: pytest
Explanation:
- The
name
field specifies the workflow’s name. - The
on
field defines when the workflow should trigger (e.g., on push to themain
branch). - The
jobs
section defines the steps to be executed. - The
uses
action is used to run pre-defined actions from the GitHub Marketplace. - The
run
step executes custom commands.
Additional Considerations
- Linting: Consider adding a step to lint your code using tools like
flake8
orblack
. - Code Formatting: Use tools like
black
to enforce consistent code formatting. - Deployment: If you’re deploying your application to a platform like Heroku or Render, you can add steps to automate the deployment process.
- Environment Variables: Store sensitive information like API keys or database credentials as secrets in your GitHub repository.
- Caching: Use caching to speed up the build process by caching dependencies.
By setting up CI with GitHub Actions, you can automate the testing and deployment process for your FastAPI application, ensuring that your code is always in a working state.