Sure! Let's walk through creating a simple FastAPI REST API endpoint that says “Hello, World” and then set up GitHub Actions to automate a part of our workflow. We'll break this down step by step, addressing basic questions like why, how, and when at each stage to ensure clarity.
Table of Contents
- Introduction to FastAPI and GitHub Actions
- Step 1: Setting Up Your Development Environment
- Step 2: Creating the FastAPI "Hello, World" Endpoint
- Step 3: Initializing a GitHub Repository
- Step 4: Setting Up GitHub Actions for Continuous Integration
- Step 5: Testing and Deployment
- Conclusion
1. Introduction to FastAPI and GitHub Actions
Why FastAPI and GitHub Actions?
-
FastAPI: A modern, fast (high-performance) web framework for building APIs with Python 3.6+ based on standard Python type hints. It's known for its speed, ease of use, and automatic documentation features.
-
GitHub Actions: A powerful CI/CD tool integrated into GitHub, allowing you to automate tasks like testing, building, and deploying your code whenever you push changes to your repository.
How Will They Work Together?
We'll create a simple FastAPI application and use GitHub Actions to automate tasks such as testing whenever we push updates to our GitHub repository. This ensures that our API remains reliable and that changes don't break existing functionality.
2. Step 1: Setting Up Your Development Environment
Why Set Up a Development Environment?
Before writing any code, you need a proper environment to ensure that your application runs smoothly and dependencies are managed correctly.
How to Set It Up?
-
Install Python: Ensure you have Python 3.6 or higher installed.
-
Create a Virtual Environment:
python3 -m venv venv
-
Upgrade pip:
pip install --upgrade pip
- Why? Ensures you have the latest package installer.
-
Install FastAPI and Uvicorn:
pip install fastapi uvicorn
- Why?
- FastAPI: The web framework.
- Uvicorn: An ASGI server to run your FastAPI application.
3. Step 2: Creating the FastAPI "Hello, World" Endpoint
Why Create a "Hello, World" Endpoint?
It's a simple starting point to ensure that everything is set up correctly and to understand the basics of handling requests and responses in FastAPI.
How to Create It?
-
Create a Python File:
Create a file named main.py in your project directory.
-
Write the Following Code:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"message": "Hello, World"}
- Explanation:
- FastAPI Instance:
app = FastAPI() creates your FastAPI application.
- Endpoint Definition: The
@app.get("/") decorator defines a GET endpoint at the root URL (/).
- Function:
read_root() returns a JSON response with the message "Hello, World".
-
Run the Application:
uvicorn main:app --reload
-
Why Uvicorn? It serves your FastAPI application.
-
What Does --reload Do? Automatically reloads the server when code changes, useful during development.
-
Test It:
4. Step 3: Initializing a GitHub Repository
Why Use GitHub?
- Version Control: Track changes to your code over time.
- Collaboration: Easily collaborate with others.
- CI/CD Integration: Utilize tools like GitHub Actions for automation.
How to Initialize?
-
Create a New Git Repository Locally:
git init
-
Add Files to the Repository:
git add .
-
Commit the Changes:
git commit -m "Initial commit with FastAPI Hello World"
-
Create a Repository on GitHub:
- Go to GitHub and create a new repository (e.g.,
fastapi-hello-world).
-
Connect Local Repository to GitHub:
git remote add origin https://github.com/your-username/fastapi-hello-world.git
-
Push the Code to GitHub:
git branch -M main
git push -u origin main
5. Step 4: Setting Up GitHub Actions for Continuous Integration
Why Use GitHub Actions?
- Automate Testing: Ensure that your code changes don't break existing functionality.
- Continuous Deployment: Automatically deploy your application when changes are merged.
- Consistency: Maintain a consistent development workflow.
How to Configure GitHub Actions?
-
Create a Workflow Directory:
GitHub Actions workflows are stored in .github/workflows/ directory.
mkdir -p .github/workflows
-
Create a Workflow File:
Create a file named ci.yml inside .github/workflows/.
-
Define the Workflow:
Add the following content to ci.yml:
name: CI
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: '3.8'
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install fastapi uvicorn pytest
- name: Run tests
run: |
pytest
- Explanation:
- name: Names the workflow "CI".
- on: Triggers the workflow on pushes and pull requests to the
main branch.
- jobs: Defines a job named
build that runs on the latest Ubuntu runner.
- steps:
- Checkout Code: Uses
actions/checkout@v2 to pull your repository's code.
- Set Up Python: Uses
actions/setup-python@v4 to install Python 3.8.
- Install Dependencies: Installs necessary Python packages.
- Run Tests: Executes tests using
pytest.
-
Commit and Push the Workflow:
git add .github/workflows/ci.yml
git commit -m "Add GitHub Actions CI workflow"
git push
6. Step 5: Testing and Deployment
Why Is Testing Important?
- Reliability: Ensures your API behaves as expected.
- Prevent Regressions: Catches bugs introduced by new changes.
How to Add Tests?
-
Create a Test File:
Create a directory named tests and add a file test_main.py.
mkdir tests
touch tests/test_main.py
-
Write a Simple Test:
In tests/test_main.py, add:
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() == {"message": "Hello, World"}
- Explanation:
- TestClient: Simulates requests to the FastAPI app.
- test_read_root: Sends a GET request to
/ and checks the response.
-
Update GitHub Actions Workflow to Include Tests:
Ensure the ci.yml includes pytest in dependencies and runs the tests.
-
Commit and Push Tests:
git add tests/
git commit -m "Add tests for Hello World endpoint"
git push
- What Happens? GitHub Actions will automatically run the CI workflow, executing the tests.
Setting Up Deployment (Optional)
If you want to deploy your FastAPI app automatically (e.g., to Heroku, AWS, etc.), you can extend the GitHub Actions workflow to include deployment steps.
7. Conclusion
Congratulations! You've successfully:
- Set Up a development environment for FastAPI.
- Created a simple "Hello, World" REST API endpoint.
- Initialized a GitHub repository to manage your code.
- Configured GitHub Actions to automate testing with each code push.
- Added tests to ensure your API functions correctly.
Why Is This Important?
- Efficiency: Automating tests saves time and reduces human error.
- Quality Assurance: Continuous Integration ensures that your codebase remains stable.
- Scalability: As your project grows, GitHub Actions can handle more complex workflows like deployments, linting, and more.
Next Steps:
- Expand Your API: Add more endpoints and functionalities.
- Enhance Testing: Include more comprehensive tests, such as integration and performance tests.
- Automate Deployment: Set up deployment pipelines to automatically deploy your API when tests pass.
By leveraging FastAPI's simplicity and GitHub Actions' automation capabilities, you can build robust, scalable, and maintainable APIs efficiently.