deploying-a-fastapi-application-with-postgresql-on-azure.html

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 an Item 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

  1. Log into Azure Portal: Navigate to the Azure portal and log in.
  2. Create a PostgreSQL Database:
  3. Click on “Create a resource” and search for “Azure Database for PostgreSQL.”
  4. Select the appropriate tier and configure the settings (server name, admin username, password, etc.).
  5. Once the database is created, note down the connection details.

  6. Set Up Tables: Connect to your Azure PostgreSQL database using a client like pgAdmin or psql 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

  1. Create a Web App:
  2. Go to the Azure portal, click on “Create a resource,” and select “Web App.”
  3. Fill in the necessary details and select the runtime stack as Python.

  4. Deploy Your Code:

  5. Use Git or FTP to deploy your FastAPI application code to the Azure Web App.
  6. 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

  1. 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"]
  1. Build and Push Docker Image:
  2. Build your Docker image: bash docker build -t your_dockerhub_username/fastapi-postgresql-azure .
  3. Push the image to Docker Hub: bash docker push your_dockerhub_username/fastapi-postgresql-azure

  4. Deploy on Azure Container Apps:

  5. 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!

SR
Syed
Rizwan

About the Author

Syed Rizwan is a Machine Learning Engineer with 5 years of experience in AI, IoT, and Industrial Automation.