FastAPI & Docker: Setup Your Project Environment
In this guide, we'll walk through the process of initializing a FastAPI project and setting up a Docker environment. This setup is crucial for developing robust and scalable backend applications. We'll cover everything from structuring your project directory to configuring your Dockerfile and main.py.
1. Initializing the Project Structure
First, let's dive into setting up your project structure. A well-organized project structure is vital for maintaining code clarity and scalability. Start by creating a root directory for your project, which we'll call backend-ai. Inside this directory, we'll establish a structure that separates our application logic, configuration, and Docker-related files.
backend-ai/
├── app/
│ ├── __init__.py
│ └── main.py
├── Dockerfile
├── requirements.txt
└── .env
app/: This subdirectory will house the core application logic. The__init__.pyfile makes theappdirectory a Python package, whilemain.pywill contain our FastAPI application.Dockerfile: This file contains instructions for building our Docker image.requirements.txt: This file lists the Python dependencies required for our project..env: This file will store environment-specific variables, such as database URLs or API keys. This helps keep sensitive information separate from your codebase and allows for easy configuration across different environments.
This structure provides a clean separation of concerns, making it easier to navigate, maintain, and scale your application. Remember, a well-organized project is a key ingredient for long-term success.
2. Creating the Dockerfile for Python
Next, let's look into creating a Dockerfile to containerize our FastAPI application. Docker allows us to package our application and its dependencies into a standardized unit, ensuring consistency across different environments. We'll create a Dockerfile that uses a Python 3.9 or 3.10 base image and sets up our application environment.
Here’s a sample Dockerfile:
FROM python:3.9-slim-buster
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
FROM python:3.9-slim-buster: This line specifies the base image for our Docker container. We're using a slim version of Python 3.9, which reduces the image size.WORKDIR /app: This sets the working directory inside the container to/app.COPY requirements.txt .: This copies therequirements.txtfile from our host machine to the container.RUN pip install --no-cache-dir -r requirements.txt: This installs the Python dependencies listed inrequirements.txt. The--no-cache-dirflag reduces the image size by preventingpipfrom caching downloaded packages.COPY . .: This copies the rest of our application code into the container.CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]: This specifies the command to run when the container starts. We're usinguvicorn, an ASGI server, to serve our FastAPI application.
This Dockerfile is designed to be efficient and straightforward, ensuring that our application is containerized correctly. Using Docker not only simplifies deployment but also ensures that our application runs consistently across various environments.
3. Setting Up requirements.txt
Setting up requirements.txt is a critical step in managing your project’s dependencies. This file ensures that everyone working on the project uses the same versions of libraries, avoiding compatibility issues and making the development process smoother. Let's look at the libraries we'll need for this project and how to add them to requirements.txt.
Here are the essential dependencies for our FastAPI project:
fastapi: The web framework we’re using to build our API.uvicorn: An ASGI server to run our FastAPI application.requests: A library for making HTTP requests.python-dotenv: A library for loading environment variables from a.envfile.azure-cognitiveservices-vision-computervision: The Azure Cognitive Services SDK for Computer Vision.azure-ai-textanalytics: The Azure Cognitive Services SDK for Text Analytics.
To include these libraries, create a requirements.txt file in the root directory of your project and list each dependency with its version (if necessary). Here’s what your requirements.txt might look like:
fastapi
uvicorn[standard]
requests
python-dotenv
azure-cognitiveservices-vision-computervision
azure-ai-textanalytics
Including specific versions in your requirements.txt can further enhance the stability of your application. This ensures that your project will continue to work as expected, even if newer versions of the libraries are released.
4. Configuring main.py with CORS Enabled
Now, let's configure main.py with CORS enabled. CORS (Cross-Origin Resource Sharing) is a security feature that browsers implement. It restricts web pages from making requests to a different domain than the one that served the web page. For our hackathon environment, we'll enable CORS to allow requests from any origin (allow *). However, keep in mind that this is not recommended for production environments due to security concerns. In a production setting, you should specify the exact origins that are allowed to access your API.
Here’s how you can configure CORS in your main.py file:
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
origins = [
"*", # Allows all origins
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"], # Allows all methods
allow_headers=["*"], # Allows all headers
)
@app.get("/")
async def read_root():
return {"status": "alive"}
- We import
FastAPIandCORSMiddlewarefromfastapi. - We create an instance of
FastAPI. - We define `origins = [