DevOps Project — Part 2
Build a REST API with FastAPI, PostgreSQL and SQLAlchemy
FastAPI is a Python framework and set of tools that allow developers to invoke commonly used functions using a REST interface.
SQLAlchemy is a package that makes it easier for Python programs to communicate with databases. Most of the time, this library is used as an Object Relational Mapper (ORM) tool, which automatically converts function calls to SQL queries and translates Python classes to tables on relational databases.
Many web, mobile, geospatial, and analytics applications use PostgreSQL as their primary data storage or data warehouse.
How to run the REST API
Get this project from Github
git clone https://github.com/LahceneDer/fastAPI_for_DevOps.git
What is REST API
REST stands for Representational State Transfer, which is a software architectural style for building distributed systems. A REST API (Application Programming Interface) is an interface that allows different software systems to communicate with each other using HTTP (Hypertext Transfer Protocol) methods, such as GET, POST, PUT, DELETE, and others.
In a REST API, resources are identified by unique URIs (Uniform Resource Identifiers), and data is transferred between client and server using a variety of standard data formats, such as JSON (JavaScript Object Notation), XML (Extensible Markup Language), or plain text.
The key principles of a RESTful API include using a client-server model, having stateless communication, and allowing for caching to improve performance. RESTful APIs are often used to provide data and functionality to web and mobile applications, allowing them to interact with servers and databases in a standardized and predictable way.
Setting up the database
- Install PostgreSQL and create your user and database
- Change this line in
database.py
to
engine=create_engine("postgresql://{YOUR_DATABASE_USER}:{YOUR_DATABASE_PASSWORD}@localhost/{YOUR_DATABASE_NAME}",
echo=True
)
Create a virtual environment
This can be done with python -m venv env
activate the virtual environment with
env/bin/activate
or
env/bin/activate
Install the requirements
pip install -r requirements.txt
Create the database
python create_db.py
Run the API
python main.py
*************************************************************************
Example ( To explain more the concept ):
FastAPI is a modern, fast, web framework for building APIs with Python, while SQLAlchemy is a popular Object-Relational Mapping (ORM) library, and PostgreSQL is a powerful open-source relational database.
Combining these technologies, you can build a FastAPI application with a PostgreSQL database using SQLAlchemy as the ORM. Here’s an overview of how you can do that:
Install the required libraries:
pip install fastapi
pip install sqlalchemy
pip install psycopg2-binary
Set up your PostgreSQL database and tables.
Define your models using SQLAlchemy’s declarative syntax. For example:
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True, index=True)
name = Column(String, index=True)
email = Column(String, unique=True, index=True)
password = Column(String)
Set up your database connection using SQLAlchemy’s create_engine
function:
from sqlalchemy import create_engine
SQLALCHEMY_DATABASE_URL = "postgresql://user:password@localhost/db_name"
engine = create_engine(
SQLALCHEMY_DATABASE_URL,
echo=True
)
Create a database session using SQLAlchemy’s sessionmaker
function:
from sqlalchemy.orm import sessionmaker
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Use FastAPI to define your API endpoints, and use SQLAlchemy to query the database. For example:
from fastapi import FastAPI, Depends, HTTPException
from sqlalchemy.orm import Session
app = FastAPI()
@app.get("/users/{user_id}")
def read_user(user_id: int, db: Session = Depends(get_db)):
user = db.query(User).filter(User.id == user_id).first()
if not user:
raise HTTPException(status_code=404, detail="User not found")
return user
That’s it …
Note: Clone the project to jump to the next step which is “ Containerize the application “
git clone https://github.com/LahceneDer/fastAPI_for_DevOps.git
Thank you !!!!