Deploying a FastAPI App
FastAPI is a modern, high-performance web framework for building APIs with Python 3.7+ based on standard Python type hints. It is known for its speed, automatic documentation, and ease of use, making it a top choice for building robust RESTful APIs and microservices.
This guide explains how to deploy a FastAPI application to Klutch.sh, both with and without a Dockerfile. It also covers installation and provides sample code to get started.
Prerequisites
- Python 3.8+
- pip installed
- Git and GitHub account
- Klutch.sh account
Getting Started: Install FastAPI
- Create a new directory for your app and set up a virtual environment:
Terminal window mkdir my-fastapi-appcd my-fastapi-apppython3 -m venv venvsource venv/bin/activate - Install FastAPI and Uvicorn:
Terminal window pip install fastapi uvicorn - Create a basic FastAPI app (
main.py
):from fastapi import FastAPIimport osapp = FastAPI()@app.get("/")def read_root():return {"message": "Hello from FastAPI on Klutch.sh!"}if __name__ == "__main__":port = int(os.environ.get("PORT", 8000))import uvicornuvicorn.run(app, host="0.0.0.0", port=port) - Add a
requirements.txt
file:Terminal window pip freeze > requirements.txt - Test locally:
Visit http://localhost:8000 to see your app running.
Terminal window python main.py
Deploying Without a Dockerfile
- Push your FastAPI app to a GitHub repository.
- Log in to Klutch.sh.
- Create a new project and give it a name.
- Create a new app:
- Select your FastAPI GitHub repository and branch
- Set the port to route traffic (usually 8000 for FastAPI)
- Choose region, compute, number of instances, and add any environment variables
- Add a start command in your app settings:
Terminal window python main.py - Click “Create” to deploy. Klutch.sh will build and deploy your app automatically.
Deploying With a Dockerfile
- Add a
Dockerfile
to your project root. Example:# Use official Python imageFROM python:3.11-slim# Set working directoryWORKDIR /app# Copy requirements and install dependenciesCOPY requirements.txt ./RUN pip install --no-cache-dir -r requirements.txt# Copy app sourceCOPY . .# Expose port (match your FastAPI app)EXPOSE 8000# Start the appCMD ["python", "main.py"] - Push your code (with Dockerfile) to GitHub.
- In Klutch.sh, follow the same steps to create a project and app, but select the Dockerfile option when prompted.
- Set the service details and environment variables as needed.
- Click “Create” to deploy. Klutch.sh will build your Docker image and deploy your app.
Note: Your FastAPI app should always listen on the PORT
environment variable as shown above.
Resources
Deploying to Klutch.sh is simple and flexible. Choose the method that best fits your workflow and project requirements.