Deploying a FastAPI Application with PostgreSQL on Azure
FastAPI is rapidly gaining traction as one of the most efficient frameworks for building APIs with Python. Coupled with PostgreSQL, a powerful relational database, deploying a FastAPI application on Azure can deliver robust, scalable, and high-performance web applications. In this article, we will walk through the entire process of deploying a FastAPI application using PostgreSQL on Azure.
What is FastAPI?
FastAPI is a modern web framework for building APIs with Python 3.6+ based on standard Python type hints. It is built on top of Starlette for the web parts and Pydantic for the data parts. FastAPI is known for its speed, automatic generation of OpenAPI documentation, and ease of use.
Use Cases for FastAPI
- Microservices: FastAPI is lightweight and efficient, making it ideal for microservices architecture where speed is crucial.
- Data-driven Applications: With its support for asynchronous programming, FastAPI is well-suited for applications that require real-time data processing.
- Prototyping: FastAPI allows developers to quickly build and iterate on APIs, making it excellent for startups and MVPs (Minimum Viable Products).
Setting Up Your Environment
Before we dive into the deployment process, let’s set up our development environment. You will need:
- Python 3.7 or later
- PostgreSQL Database
- Azure Account
Step 1: Install Required Packages
First, create a new directory for your FastAPI application and navigate into it:
mkdir fastapi-postgresql-azure
cd fastapi-postgresql-azure
Now, create a virtual environment and activate it:
python -m venv venv
source venv/bin/activate # On Windows use: venv\Scripts\activate
Next, install FastAPI, an ASGI server (like uvicorn
), and the PostgreSQL driver:
pip install fastapi uvicorn psycopg2-binary
Step 2: Create a FastAPI Application
Create a new Python file named main.py
and add the following code:
from fastapi import FastAPI
from pydantic import BaseModel
import psycopg2
app = FastAPI()
# Database connection
def get_db_connection():
conn = psycopg2.connect(
host="your_postgresql_host",
database="your_database_name",
user="your_username",
password="your_password"
)
return conn
class Item(BaseModel):
name: str
price: float
@app.post("/items/")
async def create_item(item: Item):
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute("INSERT INTO items (name, price) VALUES (%s, %s)", (item.name, item.price))
conn.commit()
cursor.close()
conn.close()
return item
Explanation of the Code
- FastAPI Initialization: We create an instance of FastAPI.
- Database Connection: The
get_db_connection
function connects to the PostgreSQL database. - Data Model: Using
Pydantic
, we define anItem
model to validate incoming data. - POST Endpoint: The
/items/
endpoint allows clients to create new items in the database.
Step 3: Create PostgreSQL Database on Azure
- Log into Azure Portal: Navigate to the Azure portal and log in.
- Create a PostgreSQL Database:
- Click on “Create a resource” and search for “Azure Database for PostgreSQL.”
- Select the appropriate tier and configure the settings (server name, admin username, password, etc.).
-
Once the database is created, note down the connection details.
-
Set Up Tables: Connect to your Azure PostgreSQL database using a client like
pgAdmin
orpsql
and run the following SQL command to create a table:
CREATE TABLE items (
id SERIAL PRIMARY KEY,
name VARCHAR(100),
price NUMERIC
);
Step 4: Deploying the Application to Azure
Option 1: Using Azure App Service
- Create a Web App:
- Go to the Azure portal, click on “Create a resource,” and select “Web App.”
-
Fill in the necessary details and select the runtime stack as Python.
-
Deploy Your Code:
- Use Git or FTP to deploy your FastAPI application code to the Azure Web App.
- Make sure to set your environment variables for database connection settings in the Azure Web App configuration.
Option 2: Using Docker on Azure Container Apps
- Create a Dockerfile:
In your application directory, create a
Dockerfile
:
FROM tiangolo/uvicorn-gunicorn-fastapi:python3.8
COPY ./app /app
RUN pip install psycopg2-binary
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"]
- Build and Push Docker Image:
- Build your Docker image:
bash docker build -t your_dockerhub_username/fastapi-postgresql-azure .
-
Push the image to Docker Hub:
bash docker push your_dockerhub_username/fastapi-postgresql-azure
-
Deploy on Azure Container Apps:
- In the Azure portal, create a Container App, and configure it to pull the Docker image from Docker Hub.
Step 5: Testing Your Application
Once deployed, your FastAPI application should be accessible via the Azure Web App or Container App URL. Test the API using tools like Postman or curl
:
curl -X POST "https://your_app_url/items/" -H "Content-Type: application/json" -d '{"name": "Item1", "price": 12.99}'
Troubleshooting Tips
- Database Connection Issues: Ensure that your PostgreSQL server allows connections from the Azure service by configuring the firewall settings.
- CORS Errors: If you plan to access your API from a frontend application, configure CORS settings in FastAPI to allow cross-origin requests.
- Logs: Use Azure logs to monitor your application and diagnose any issues.
Conclusion
Deploying a FastAPI application with PostgreSQL on Azure is a straightforward process that enables developers to build high-performance APIs. With the steps outlined above, you can leverage the power of FastAPI and PostgreSQL to create scalable applications in the cloud. Whether you're building microservices or data-driven applications, Azure provides a robust platform for deployment. Happy coding!