Creating a web application with FastAPI and SQLAlchemy: Part 1

Posted by

FastAPI + SQLAlchemy = создание web приложения ч. 1

FastAPI + SQLAlchemy = создание web приложения ч. 1

FastAPI and SQLAlchemy are two powerful tools that can be used to create web applications with ease. FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.7+ based on standard Python type hints. It is also able to generate interactive API documentation automatically. On the other hand, SQLAlchemy is a SQL toolkit and Object-Relational Mapping (ORM) that provides a set of high-level operations and performs database operations using Python methods rather than SQL queries.

When combining FastAPI with SQLAlchemy, you can easily create web applications that handle database operations efficiently and provide a robust API for client communication. In this article, we will discuss the basics of using FastAPI and SQLAlchemy together to create a simple web application.

Setting up the environment

First, you need to have Python 3.7+ installed on your system. You can then create a virtual environment for your project using the following command:

python3 -m venv myenv

Next, activate the virtual environment:

source myenv/bin/activate

Once the virtual environment is activated, you can install FastAPI and SQLAlchemy using the following commands:

pip install fastapi
pip install sqlalchemy

Now that you have set up the environment, you are ready to start building your web application using FastAPI and SQLAlchemy.

Creating a simple web application

For this example, let’s create a simple web application that allows users to create, read, update, and delete (CRUD) tasks in a to-do list. We will define a Task model using SQLAlchemy and create API endpoints to perform CRUD operations on the tasks.

First, create a new file called main.py and import the necessary modules:


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

Next, create an instance of the FastAPI app and connect it to a SQLite database using SQLAlchemy:


app = FastAPI()

SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db"
engine = create_engine(SQLALCHEMY_DATABASE_URL)

SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Base = declarative_base()

Now, define the Task model and create the corresponding table in the database:


from sqlalchemy import Column, Integer, String

class Task(Base):
__tablename__ = "tasks"

id = Column(Integer, primary_key=True, index=True)
title = Column(String, index=True)
description = Column(String, index=True)

Finally, define the API endpoints to perform CRUD operations on the tasks:


from fastapi import HTTPException

@app.post("/tasks/")
async def create_task(task: Task):
db = SessionLocal()
db.add(task)
db.commit()
db.refresh(task)
return task

@app.get("/tasks/{task_id}")
async def read_task(task_id: int):
db = SessionLocal()
task = db.query(Task).filter(Task.id == task_id).first()
if task is None:
raise HTTPException(status_code=404, detail="Task not found")
return task

# ... (additional CRUD endpoints for updating and deleting tasks)

With these basic components in place, you can now run the FastAPI app and start testing the CRUD operations on the tasks. In the next part of this series, we will continue to build upon this example and add more functionality to the web application.

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

Продолжение про работу с ORM
https://youtu.be/-d3hjMLp8EQ?si=5uhcc8ky4FIh59RA

@Sunwait-nsk
6 months ago

спасибо! мне понравился подход к подаче материала, при таком коротком видео учтены все нюансы, которые мне например были непонятны!

@79fz270704
6 months ago

Хороший видос, спасибо! Я думаю, что таки пора использовать poetry.

@captainkryuk1899
6 months ago

Крутое видео, только
– вместо удаленного сервера лучше использовать wsl, сейчас к нему можно подключить docker, pycharm и вся инфраструктура будет внутри wsl2 и с виндой не надо будет взаимодействовать
– для разрешения зависимостей сейчас удобнее всего работать с poetry, описывать преимущества не буду, можно просто любое видео о нем посмотреть
– для миграций необходимо использовать alembic, когда появится проблема, когда нужно будет откатиться назад, будет тяжело ее решить без миграций
– у fastapi есть встроенная документация swagger по адресу /docs (если в app не меняли), ее использовать удобнее, чем postman

@Allsee77
6 months ago

Вопрос: а зачем делать именно пакеты? (с файлом __init__.py). Например, если создать просто папку routers и реализовать роутеры по той же схеме, всё работает аналогично.

@devolver80
6 months ago

Круто, что объясняешь, почему использовал те или иные технологии, а также приводишь альтернативные способы. Очень полезно и содержательно. Спасибо!

@monoteis
6 months ago

Мне кажется, в PyCharm сложнее организовать проект, чем в VS Code. Много ненужных функций через UI, которых можно сделать в 2 клика в командной строке

@user-iv5co4lu9g
6 months ago

Всё отлично кэп, но главная фишка FastAPI это его полная поддержка асинхронности, в том числе и асинхронного взаимодействия с базой данных без каких либо проблем, если хоть немного разбираешься с библиотекой asyncio. А тут я увидел нечто подобное с DRF, просто другая реализация, но паттерн проектирования то тот – же. MVC. Нет асинхронности, а это большое упущение в презентации этого фреймворка!

@user-oc5sd1jw4n
6 months ago

А про миграции раскажете ?

@maximgursky
6 months ago

Крутой ролик. Про async ещё было бы интересно

@fromua2918
6 months ago

Для чого postman, коли є вбудовна документація (Swagger), нащо ця срака з залежностями? От прям не дивуюсь, що у вас на болтах все так погано, нічого не можете по-людьски зробити

@slashfast
6 months ago

По поводу лицензии JetBrains: студентам до сих пор продлевают

@kenybond6564
6 months ago

1000 подписчиков и 1000 просмотров – хорошая вовлечённость 👍

@linarusmanow7838
6 months ago

Красава, удачи тебе !

@user-vf7pc4tn9z
6 months ago

будет подрбный курс по фастапи?

@Rnk322
6 months ago

Ролик полезный, жаль код не посмотреть из-за нерабочего гитхаба(

@futhep336
6 months ago

Смотреть одно удовольствие, подача материала 5/5👍

@AlexandrKalinovsky
6 months ago

Вы упомянули курсы, что занимались самообучением… Я тоже учусь с помощью курсов. Было бы интересно узнать как вы проходили свой путь в программировании, какие трудности были, может какие-то советы дадите. Спасибо заранее
Кстати, для новичков это очень интересная и полезная тема, по себе знаю. Может это повод для отдельного видео?

@user-it3yo1sn6i
6 months ago

По вашему мнению какой из трех популярных фреймфорков новичку осваивать легче?

@user-ih8vs8xw2c
6 months ago

продолжай в том же духе ❤