FastAPI - Getting Started & Docker Integration
Tags: fastapi, python, webdev
Published: 2023-09-18 09:00:17

---
title: FastAPI - Getting Started & Docker Integration
published: true
description: Getting Started with FastAPI, a high-performance, web framework for building APIs with Python
tags: fastapi, python, webdev
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t34tcg5n1jxzaquly8jb.png
canonical_url: https://docs.appseed.us/technologies/fastapi/getting-started/
---
Hello Coders!

This article explains how to [start with FastAPI](https://docs.appseed.us/technologies/fastapi/getting-started/) and later, properly [Dockerize a FastAPI project](https://docs.appseed.us/technologies/fastapi/docker-integration/). 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:

```bash
pip install fastapi
```

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

```bash
pip install uvicorn
```

---

## ✅ **Creating a FastAPI App**

Here's a basic example of a FastAPI application:

```python
from fastapi import FastAPI

app = FastAPI()

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

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

---

## ✅ **Running the FastAPI App**

You can run your FastAPI app using `uvicorn`:

```bash
uvicorn main:app --reload
```

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:

```python
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}
```

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:

```python
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
```

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:

```Dockerfile
# 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"]
```

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
```

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:

```bash
docker build -t my-fastapi-app .
```

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:

```bash
docker run -d -p 8000:8000 my-fastapi-app
```

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](https://fastapi.tiangolo.com/).

---

## ✅ Resources 

- 👉 Access [AppSeed](https://appseed.us/) and start fast your next project
- 👉 [Deploy Projects on Aws, Azure and Digital Ocean](https://www.docs.deploypro.dev/) via **DeployPRO**
- 👉 Create an amazing landing page with [Simpllo, an open-source site builder](https://www.simpllo.com/)
- 👉 [Django App Generator](https://app-generator.dev/django/) - A 2nd generation App Builder