DEV Community

Cover image for FastAPI - Getting Started & Docker Integration
Sm0ke
Sm0ke

Posted on • Originally published at docs.appseed.us

FastAPI - Getting Started & Docker Integration

Hello Coders!

This article explains how to start with FastAPI and later, properly Dockerize a FastAPI project. For newcomers, FastAPI is a modern, high-performance, web framework for building APIs with Python.

It's designed to be easy to use, and efficient, and to provide automatic generation of interactive documentation. FastAPI is built on top of Starlette and Pydantic, and it leverages Python 3.6+ type hints for request and response validation. Thanks for reading!


Installation

You can install FastAPI using pip:

pip install fastapi
Enter fullscreen mode Exit fullscreen mode

You'll also want to install a web server like uvicorn to serve your FastAPI application:

pip install uvicorn
Enter fullscreen mode Exit fullscreen mode

Creating a FastAPI App

Here's a basic example of a FastAPI application:

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def read_root():
    return {"message": "Hello, World"}
Enter fullscreen mode Exit fullscreen mode

Save this code to a Python file (e.g., main.py).


Running the FastAPI App

You can run your FastAPI app using uvicorn:

uvicorn main:app --reload
Enter fullscreen mode Exit fullscreen mode

This command tells uvicorn to run the app instance in the main.py file and enables auto-reloading for development.


Routes and Path Parameters

FastAPI makes it easy to define routes and path parameters. Here's an example that includes path parameters:

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def read_root():
    return {"message": "Hello, World"}

@app.get("/items/{item_id}")
async def read_item(item_id: int, query_param: str = None):
    return {"item_id": item_id, "query_param": query_param}
Enter fullscreen mode Exit fullscreen mode

In this example, we define a route /items/{item_id} that takes an item_id as a path parameter and an optional query_param as a query parameter.


Request and Response Models

FastAPI allows you to define request and response models using Pydantic models. Here's an example:

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str
    description: str = None
    price: float
    tax: float = None

@app.post("/items/")
async def create_item(item: Item):
    return item
Enter fullscreen mode Exit fullscreen mode

In this example, we define a Pydantic model Item for the request body of the POST request to /items/.
FastAPI automatically validates and parses the incoming JSON data based on this model.


Automatic Documentation

One of FastAPI's standout features is its automatic generation of interactive API documentation.
To access the documentation, go to http://localhost:8000/docs in your web browser while your FastAPI app is running.


Validation and Serialization

FastAPI automatically validates incoming requests and serializes responses based on the Pydantic models you define. If data doesn't match the expected model, FastAPI will return validation errors.


Dockerizing a FastAPI project involves creating a Docker image that contains your FastAPI application and its dependencies.

Here's a step-by-step guide on how to dockerize a FastAPI project:


Create a Dockerfile

In your FastAPI project directory, create a file named Dockerfile (without any file extension) with the following content:

# Use a base Python image
FROM python:3.x

# Set environment variables
ENV PYTHONUNBUFFERED 1
ENV PYTHONDONTWRITEBYTECODE 1

# Set the working directory inside the container
WORKDIR /app

# Copy the requirements file into the container
COPY requirements.txt /app/

# Install project dependencies
RUN pip install -r requirements.txt

# Copy the rest of the application code into the container
COPY . /app/

# Expose the port your FastAPI app will run on
EXPOSE 8000

# Command to run your FastAPI app with uvicorn
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
Enter fullscreen mode Exit fullscreen mode

Make sure to replace 3.x with the Python version you are using. This Dockerfile sets up a basic environment for running a FastAPI application.


Create a .dockerignore File

In the same directory as your Dockerfile, create a .dockerignore file to specify files and directories that should be excluded when copying files into the Docker image. For example:

__pycache__
*.pyc
*.pyo
*.pyd
*.db
*.sqlite3
Enter fullscreen mode Exit fullscreen mode

This helps keep unnecessary files out of the Docker image.


Build the Docker Image

Open a terminal and navigate to your project directory containing the Dockerfile. Run the following command to build the Docker image:

docker build -t my-fastapi-app .
Enter fullscreen mode Exit fullscreen mode

Replace my-fastapi-app with a name you choose for your Docker image. The . at the end specifies the build context (current directory).


Run the Docker Container

Once the image is built, you can run a Docker container from it:

docker run -d -p 8000:8000 my-fastapi-app
Enter fullscreen mode Exit fullscreen mode

This command maps port 8000 inside the container to port 8000 on your host system. Adjust the port mapping as needed.


Access Your FastAPI App

Your FastAPI app should now be running inside a Docker container. You can access it by visiting http://localhost:8000 in your web browser or making API requests to that address.


✅ In Summary

These are just some of the basics of FastAPI. It provides many more features for building robust and efficient APIs, including dependency injection, authentication, and more.

FastAPI's official documentation is excellent and provides in-depth information on all of its features - FastAPI Official Documentation.


✅ Resources

Top comments (0)