Connect Python to an Oracle DB with FastAPI and SQLAlchemy
Python is a popular programming language for developing web applications, and FastAPI is a modern web framework for building APIs with Python. If you need to connect your Python application to an Oracle database, SQLAlchemy is a powerful ORM that can help streamline the process.
In this article, we will walk you through the steps to connect Python to an Oracle database using FastAPI and SQLAlchemy.
Step 1: Install required libraries
First, make sure you have Python installed on your machine. You can install FastAPI and SQLAlchemy using pip:
pip install fastapi
pip install sqlalchemy
pip install cx_oracle
Step 2: Create a FastAPI application
Create a new Python file for your FastAPI application. Import the required libraries:
from fastapi import FastAPI
from sqlalchemy import create_engine
Create an instance of the FastAPI class:
app = FastAPI()
Step 3: Configure SQLAlchemy for Oracle
Create a SQLAlchemy engine with the Oracle database URL:
database_url = 'oracle+cx_oracle://username:password@host:port/service'
engine = create_engine(database_url)
Step 4: Define database models
Create your database models using SQLAlchemy’s ORM:
from sqlalchemy import Column, Integer, String, Text, Date, DateTime
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
Define your models:
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
Step 5: Create database tables
Create the database tables using the metadata object:
Base.metadata.create_all(bind=engine)
Step 6: Run the FastAPI application
Add routes to your FastAPI application and run it using uvicorn:
if __name__ == '__main__':
import uvicorn
uvicorn.run("app:app", host="0.0.0.0", port=8000, reload=True)
With these steps, you should now be able to connect your Python application to an Oracle database using FastAPI and SQLAlchemy. Happy coding!
Timestamps:
0:00 – Introduction
2:02 – Create an Oracle Autonomous Database for Free
8:59 – Connect to the Oracle Database with SQL Developer
10:58 – Connect to an Oracle DB with Python
18:45 – Connect to an Oracle Database with Python and SQLAlchemy
20:56 – Create a table with SQLAlchemy on an Oracle Database
29:45 – Getting a DB connection by the API endpoints on FastAPI
You can watch previous video on how to Learn FastAPI in 22 minutes in this video: https://www.youtube.com/watch?v=Rfyq-bFnGwU