How Can You Launch Your FastAPI App into the Clouds Without Breaking a Sweat?

Launching FastAPI to the Cloud: Simplified Steps for GCP and AWS Integration

How Can You Launch Your FastAPI App into the Clouds Without Breaking a Sweat?

Deploying your FastAPI app on cloud platforms like AWS (Amazon Web Services) or GCP (Google Cloud Platform) doesn’t have to be rocket science. It might look overwhelming at first, but with a bit of guidance, you’ll be launching your app into the cloud smoothly.

Understanding FastAPI

Let’s get on the same page about what FastAPI is. This web framework is perfect if you’re coding in Python 3.7+ and need to build APIs swiftly. FastAPI supports asynchronous programming and relies on standard Python type hints, making it a breeze for backend development.

Getting Your FastAPI App on Google Cloud Platform (GCP):

Alright, to get started with GCP, you’ll need to have a few things set up:

  • A GCP account with an active billing setup.
  • Google Cloud CLI (gcloud) to interact with GCP.
  • Python and FastAPI installed in your project.

Here’s a basic outline for your FastAPI application:

from fastapi import FastAPI

app = FastAPI()

@app.get("/", tags=["root"])
async def root():
    return {"message": "Hello World"}

To deploy this on GCP’s App Engine, you need to have a app.yaml file like this:

runtime: python37
entrypoint: gunicorn -w 4 -k uvicorn.workers.UvicornWorker main:app

This file tells App Engine to use Python 3.7 and the gunicorn server with uvicorn workers.

Here’s how you can push your application to Google App Engine:

  1. Create the App: Use the gcloud CLI to create your app.

    gcloud app create
    

    Choose a region close to your users for faster response times.

  2. Deploy the App: Run the following command to deploy.

    gcloud app deploy app.yaml
    

    If you have multiple projects, specify the project ID:

    gcloud app deploy app.yaml --project your-project-id
    
  3. Access Your App: Once deployed, your app will be live at your-project-id.appspot.com. You can open it with:

    gcloud app browse
    
  4. Testing and Logging: Test with Postman or any similar tool. For logs, you can tail them directly from the cloud shell:

    gcloud app logs tail -s default
    

Another Way on GCP: Google Cloud Run

If you’re looking for a fully managed serverless platform, Google Cloud Run is an excellent choice. Here’s a breakdown of what you need:

  • GCP account.
  • Google Cloud CLI.
  • Docker.
  • Python installed.

Set up a basic FastAPI application like before, but get Docker involved. Here’s a simple Dockerfile:

FROM python:3.11.3
ENV PYTHONUNBUFFERED True
RUN pip install --upgrade pip
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
ENV APP_HOME /root
WORKDIR $APP_HOME
COPY . .
EXPOSE 8080
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8080"]

Then if you’re managing dependencies with Poetry, generate a requirements.txt:

poetry export -f requirements.txt --output requirements.txt

Deploy using Cloud Run:

gcloud run deploy sample --port 8080 --source .

Voila! Your app will be on Cloud Run and you’ll have a URL to access it.

Deploying FastAPI on AWS:

Jumping to AWS now, here’s what you need:

  • AWS account.
  • AWS CLI.
  • Docker.
  • Python installed.

One efficient way to handle deployment on AWS is using Porter. Porter automates many tasks and simplifies deploying to AWS.

Here’s how to get started:

  1. Create your FastAPI app like before.
  2. Push it into a Docker container, using a Dockerfile similar to the one we used for Cloud Run.
  3. Use Porter to manage the deployment, specifying all necessary configurations.

For those integrating continuous integration/continuous delivery (CI/CD), GitHub Actions can be super handy. Here’s a basic GitHub Actions workflow to deploy your FastAPI app to AWS:

name: Deploy to AWS

on:
  push:
    branches:
      - main

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v2

      - name: Login to AWS
        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-west-2'

      - name: Build and push image
        run: |
          docker build -t my-fastapi-app .
          docker tag my-fastapi-app:latest ${{ secrets.AWS_ACCOUNT_ID }}.dkr.ecr.us-west-2.amazonaws.com/my-fastapi-app:latest
          docker push ${{ secrets.AWS_ACCOUNT_ID }}.dkr.ecr.us-west-2.amazonaws.com/my-fastapi-app:latest

      - name: Deploy to EC2
        run: |
          ssh -o "StrictHostKeyChecking=no" ec2-user@your-ec2-instance 'docker pull ${{ secrets.AWS_ACCOUNT_ID }}.dkr.ecr.us-west-2.amazonaws.com/my-fastapi-app:latest && docker-compose up -d'

Push your code to GitHub, and the pipeline will take care of building the Docker image, pushing it to AWS ECR, and deploying it to your EC2 instance.

Thoughts on Deployment

Deploying your FastAPI app on cloud platforms like AWS or GCP can really streamline your workflow and provide the scalability you need. Whether using GCP’s App Engine, Cloud Run, or AWS with Porter and GitHub Actions, each option brings its own set of tools and benefits.

Make sure you’re also setting up proper logging, monitoring, and security measures. This ensures your application runs smoothly and stays secure.

Deploying may sound intimidating, but once you break it down into these steps, it’s a lot more manageable. Happy coding and deploying! 💻🚀