How To Dockerize a Simple Rest API with Python FastAPI
FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.7+ based on standard Python type hints. It also supports Asyncio. In this article, we will walk through the process of dockerizing a simple Rest API built using FastAPI.
Step 1: Install FastAPI and Uvicorn
First, we need to install FastAPI and Uvicorn using pip:
pip install fastapi
pip install uvicorn
Step 2: Create a Simple API
Next, we will create a simple REST API using FastAPI. Below is a basic example of a FastAPI app:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
Step 3: Run the API
To run the API, we can use Uvicorn which provides a lightweight ASGI server:
uvicorn main:app --reload
Step 4: Create a Dockerfile
Now, we can create a Dockerfile to build and run our FastAPI app. Below is an example of a Dockerfile:
FROM tiangolo/uvicorn-gunicorn-fastapi:python3.8
COPY ./app /app
# EXPOSE 80
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"]
Step 5: Build and Run the Docker Image
We can now build the Docker image and run our FastAPI app inside a container:
docker build -t fastapi-app .
docker run -d --name fastapi-container -p 80:80 fastapi-app
Step 6: Test the API
Finally, we can test our Dockerized FastAPI app by accessing it through the browser or using tools such as curl or Postman.
That’s it! We have successfully dockerized a simple Rest API built with FastAPI. Dockerizing applications is a great way to ensure consistency and portability across different environments.