Setting up the Project and Connecting to the Database: FastAPI Series – Blog API Part 1

Posted by

FastAPI Series: Blog API Part 1

FastAPI Series: Blog API Part 1

Project setup and Database Connection

Welcome to the FastAPI Series where we will be building a Blog API using the FastAPI framework. In this first part, we will cover the project setup and establishing a connection to a database.

Project Setup

To get started with our project, we first need to set up a new Python virtual environment. You can do this by running the following commands in your terminal:


$ python3 -m venv venv
$ source venv/bin/activate

Next, we need to install FastAPI and any other dependencies we will be using in our project:


$ pip install fastapi
$ pip install uvicorn
$ pip install sqlalchemy

Database Connection

For our blog API, we will be using SQLAlchemy as our ORM to interact with a database. Let’s create a new Python file called db.py and establish a connection to our database:


from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

SQLALCHEMY_DATABASE_URL = "sqlite:///./blog.db"

engine = create_engine(SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False})
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Base = declarative_base()

With this setup, we now have a connection to our database that we can use to define our models and interact with data in our blog API.

Stay tuned for the next part of the FastAPI Series where we will be covering the creation of our blog API endpoints!

0 0 votes
Article Rating
6 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@vaibhavgupta5776
7 months ago

Can you please share the repo it will really help to catch up with the tutorial

@mdaslamknl
7 months ago

Can you share the code

@richardmcsharry
7 months ago

brilliant tutorial…in fact the whole FastAPI series you've created is awesome. One improvement, please get a better mic or turn up your input gain so we can here you more easily

@manuelantunez4894
7 months ago

i Cant hear anything

@alexandrodisla6285
7 months ago

Can you provide the github repo?

@juno7183
7 months ago

very thank you bro. I do my test task from interview on your guide