Build a RESTful API in Python Using Flask and PostgreSQL

How to Build a RESTful API in Python Using Flask and PostgreSQL

In this tutorial, we will walk through creating a simple yet organized Python API using Flask and PostgreSQL. We will use SQLAlchemy to interact with the database and organize our code into separate modules for maintainability. The goal is to create a clean, scalable structure for building and expanding the application as needed.

In this tutorial, we are going to use the below directory structure.

  • app.py: The main entry point for the application.
  • models: Contains database models.
  • controllers: Handles HTTP requests and responses.
  • repository: Responsible for database operations.
  • services: Contains business logic.
  • serializers: Validates and serializes input data.
  • utils: Utility functions, such as password handling

Step By Step Guide To Build an API

Step 1: Project Setup

We begin by setting up a Python project and installing the necessary packages. To install Flask, SQLAlchemy, and psycopg2 (the PostgreSQL adapter for Python), open the terminal and run the following command

Step 2: Database Configuration

Create a file in the configs directory and add below code snippet below –

Step 3: Setting Up the Database Models

Now let’s set database models. Database models usually represent our database table. It is very easy to manage database queries using ORM. It prevents SQL injection automatically. so create a file in the model’s directory and add below code snippet:

Now let’s set up our user model. Create another file in the model’s directory and add below code snippet below –

Step 4: Controllers Layer

Controllers basically control our data flow throughout the request/response cycle. We set all our routes here so let’s create a file in the controller’s directory and add below code snippet below –

Step 5: Service Layer

This layer contains our core logic. All kinds of things like checking duplicacy and hashing of passwords etc. We usually do that in the service layer. Create a file in the services directory and add the below lines –

Step 6: Repository Layer

This layer communicates with the Database. create a file in the repository directory and add below code snippet below –

Step 7: Serializers layer

Serializers are basically a way to serialize our output. We can control what should be the contents of the output because we don’t want to send the hashed password in the API response. Create a file in the serializers directory and add below code snippet below –

Step 8: Utils layer

The utils layer basically contains small utility functions that can be reused in our app. Create a file in the utils directory and add below code snippet below –

Step 9: Entry point

At last, create an entry point for our application. Our application will be run through this file. create a file at the root and add the below code –

Step 10: Running our application

Add your database URL in the config file open the terminal and use the command –

python3 app.pyyour application with start to run on http://localhost:5000 and you can access your routes as follows –

Conclusion

This Python API is built using Flask for handling web requests and SQLAlchemy for interacting with a PostgreSQL database. The application follows a modular structure, making it easy to maintain and expand as it grows. Here’s a breakdown of the key components:

app.py — This is the main entry point of the app. It sets up the Flask application, registers routes, and connects to the database.
models — This file contains the database models, defining the structure of the tables and handling database operations.
controllers — These are the functions that handle incoming HTTP requests, validate input, and send appropriate responses.
repository — This layer is responsible for directly interacting with the database, performing CRUD (Create, Read, Update, Delete) operations.
services — Here is where the core business logic resides, including processing data and managing interactions with the repository layer.
serializers — These ensure that input data is validated and serialized correctly before passing it to the services layer.
utils — This folder contains utility functions for tasks like password hashing and verification.

This structure keeps the application organized, easy to extend, and clean. By separating concerns into specific files and directories, the application can grow and adapt without becoming unmanageable.

Leave a Reply

Your email address will not be published. Required fields are marked *

Amandeep Singh

Amandeep Singh (Tech Expert)

Amandeep is a dedicated tech enthusiast with a passion for simplifying complex concepts. With a keen eye for emerging technologies and a knack for sharing knowledge, he breaks down intricate tech topics into easy-to-understand explanations with his blogs. With a keen interest in emerging technologies, Amandeep strives to make technology accessible to everyone.

Leave a Reply

Your email address will not be published. Required fields are marked *

India

Dibon Building, Ground Floor, Plot No ITC-2, Sector 67 Mohali, Punjab (160062)

Business: +91-814-611-1801
USA

7110 Station House Rd Elkridge MD 21075

Business: +1-240-751-5525
Dubai

DDP, Building A1, IFZA Business Park - Dubai Silicon Oasis - Dubai - UAE

Business: +971 565-096-650
Australia

G01 , 8 Meririvlle Road, Kellyville Ridge NSW 2155 , Australia

Automate your business processes to boost your ROI.
Get updates straight to your inbox