Все о FastAPI за 30 минут

Posted by


FastAPI is a modern, fast (high-performance) web framework for building APIs with Python 3.6+ based on standard Python type hints. It is designed to be easy to use, fast to develop with, and simple to deploy.

In this tutorial, I will guide you through creating a simple FastAPI project in just 30 minutes. By the end of this tutorial, you will have a basic understanding of how FastAPI works and how to create and deploy a simple API using FastAPI.

Step 1: Setup a Virtual Environment

First, create a new directory for your project and navigate to that directory in your terminal. Then create a new virtual environment using the following command:

python3 -m venv venv

Activate the virtual environment by running:

source venv/bin/activate

Step 2: Install FastAPI and Uvicorn

Next, install FastAPI and Uvicorn using pip:

pip install fastapi uvicorn

Step 3: Create a FastAPI App

Create a new Python file called main.py in your project directory. In this file, import FastAPI and create a new FastAPI app instance like this:

from fastapi import FastAPI

app = FastAPI()

Step 4: Hello World API

Now, let’s create a simple "Hello World" endpoint. Add the following code to your main.py file:

@app.get("/")
async def read_root():
    return {"message": "Hello, World"}

This code defines a new endpoint at the root URL that returns a JSON object with a message saying "Hello, World".

Step 5: Run the FastAPI App

To run your FastAPI app, use the Uvicorn server. Start the server by running the following command:

uvicorn main:app --reload

This command tells Uvicorn to run the app defined in the main.py file and automatically reload the server when changes are made to the code.

Step 6: Test the Hello World Endpoint

Open your web browser and navigate to http://localhost:8000/. You should see a JSON response with the message "Hello, World".

Step 7: Create a User API

Now, let’s create another endpoint that returns information about a user. Add the following code to your main.py file:

@app.get("/user/{user_id}")
async def read_user(user_id: int):
    return {"user_id": user_id, "name": "John Doe"}

This code defines a new endpoint that takes a user_id as a path parameter and returns a JSON object with the user’s ID and name.

Step 8: Test the User Endpoint

Open your web browser and navigate to http://localhost:8000/user/1. You should see a JSON response with the user ID and name.

Step 9: Deployment

To deploy your FastAPI app, you can use a server like Gunicorn. First, install Gunicorn using pip:

pip install gunicorn

Then, you can start the Gunicorn server by running the following command:

gunicorn -w 4 -k uvicorn.workers.UvicornWorker main:app

This command tells Gunicorn to run the app defined in the main.py file using the Uvicorn worker and 4 worker processes.

Congratulations! You have successfully created and deployed a simple FastAPI project in just 30 minutes. FastAPI is a powerful and easy-to-use framework for building APIs with Python, and I hope this tutorial has given you a good introduction to it. Happy coding!

0 0 votes
Article Rating

Leave a Reply

20 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@evan_kirk
9 days ago

WSGi/ASGI – это стандартизация интерфейса взаимодействия нашего приложения с веб-сервером, например, gunicorn/uvicorn

@СергейКоваль-ь1в
9 days ago

А у меня что-то не пошло
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [12592] using StatReload
Process SpawnProcess-1:
Traceback (most recent call last):
File "C:UsersAcer.pyenvpyenv-winversions3.12.4Libmultiprocessingprocess.py", line 314, in _bootstrap
self.run()
File "C:UsersAcer.pyenvpyenv-winversions3.12.4Libmultiprocessingprocess.py", line 108, in run
self._target(*self._args, **self._kwargs)
File "C:UsersAcerDesktopОбучение6.09.2024venvLibsite-packagesuvicorn_subprocess.py", line 80, in subprocess_started target(sockets=sockets)
File "C:UsersAcerDesktopОбучение6.09.2024venvLibsite-packagesuvicornserver.py", line 65, in run
return asyncio.run(self.serve(sockets=sockets))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:UsersAcer.pyenvpyenv-winversions3.12.4Libasynciorunners.py", line 194, in run
return runner.run(main)
^^^^^^^^^^^^^^^^
File "C:UsersAcer.pyenvpyenv-winversions3.12.4Libasynciorunners.py", line 118, in run
return self._loop.run_until_complete(task)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:UsersAcer.pyenvpyenv-winversions3.12.4Libasynciobase_events.py", line 687, in run_until_complete
return future.result()
^^^^^^^^^^^^^^^
File "C:UsersAcerDesktopОбучение6.09.2024venvLibsite-packagesuvicornserver.py", line 69, in serve
await self._serve(sockets)
File "C:UsersAcerDesktopОбучение6.09.2024venvLibsite-packagesuvicornserver.py", line 76, in _serve
config.load()
File "C:UsersAcerDesktopОбучение6.09.2024venvLibsite-packagesuvicornconfig.py", line 434, in load
self.loaded_app = import_from_string(self.app)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:UsersAcerDesktopОбучение6.09.2024venvLibsite-packagesuvicornimporter.py", line 19, in import_from_string
module = importlib.import_module(module_str)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:UsersAcer.pyenvpyenv-winversions3.12.4Libimportlib__init__.py", line 90, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "<frozen importlib._bootstrap>", line 1387, in _gcd_import
File "<frozen importlib._bootstrap>", line 1360, in _find_and_load
File "<frozen importlib._bootstrap>", line 1331, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 935, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 995, in exec_module
File "<frozen importlib._bootstrap>", line 488, in _call_with_frames_removed
File "C:UsersAcerDesktopОбучение6.09.2024main.py", line 3, in <module>
from database import SessionLocal, engine, Base
File "C:UsersAcerDesktopОбучение6.09.2024database.py", line 7, in <module>
engine = create_engine(SQLALCHEMY_URL, create_engine={
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "<string>", line 2, in create_engine
File "C:UsersAcerDesktopОбучение6.09.2024venvLibsite-packagessqlalchemyutildeprecations.py", line 281, in warned
return fn(*args, **kwargs) # type: ignore[no-any-return]
^^^^^^^^^^^^^^^^^^^
File "C:UsersAcerDesktopОбучение6.09.2024venvLibsite-packagessqlalchemyenginecreate.py", line 697, in create_engine
raise TypeError(
TypeError: Invalid argument(s) 'create_engine' sent to create_engine(), using configuration SQLiteDialect_pysqlite/QueuePool/Engine. Please check that the keyword arguments are appropriate for this combination of components.

@ЮрийЮрий-д8у
9 days ago

Проблема каждого, кто снимает такие ролики, — это отсутствие живых примеров. Автор, вот таск, вот то-то. Где живой пример, понятный ребёнку: это яблоко, а это банан?

@РонанОбвинитель
9 days ago

Дядь, ты сразу подавай нормальные примеры кода и юзай менеджеры контекстов:

import os

from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import sessionmaker

DATABASE_URL = os.environ.get("DATABASE_URL")

engine = create_async_engine(DATABASE_URL, echo=True, future=True)

async def get_pg_session() -> AsyncSession:
async_session = sessionmaker(
engine, class_=AsyncSession, expire_on_commit=False
)

async with async_session() as session:
yield session

@Torvalds_
9 days ago

люди которые изучают FastAPI месяц: "Да да пошли мы нахер"

@bfdhtfyjhjj
9 days ago

services.user строка 17 у вас вместо точки запятая, как при этом нет ошибки я вообще не понял

@RCCopterChannel
9 days ago

Django тоже может асинхронно обрабатывать запросы. К примеру вебсокеты.

@IvaNFallout
9 days ago

Определение ручек через async def не делает сервис асинхронным, ибо работа с БД тут синхронная

@foxmulder681
9 days ago

безасинхронный асинхронный сервис получился

@romankim3423
9 days ago

можно ссылку на гит?

@АндрейКулагин-е1ш
9 days ago

30 минут смотрел почти 4 часа))

@mk3mk3mk
9 days ago

Выезжай, наезжай :))

@hhhhhhhhhgfh
9 days ago

Не совсем понимаю, как программа в функции get_db() дойдёт до блока finally, если она постоянно возвращает соединения с базой 🤔 Можно пояснительную бригаду)

@bgs12
9 days ago

спасибо за ролик.
у меня пайчарм ругается на (https://youtu.be/1ZlOEoCWkQU?t=386), пишет что порт должен быть не "post", а "port"

@vladvlad3544
9 days ago

А FastAPI не ООП фреймворк?

@ДмитрийДунаев-р5т
9 days ago

Крутой базовый тэмплейт на все случаи жизни. Повторил, всё работает, за исключением одной опечатки, которую уже в каментах ниже нашли. Спасибо, схоронил! Буду использовать вместо DRF

@ЭраджИмомбердиев
9 days ago

Крутой ролик автору способа

@program_wolf
9 days ago

Можно ли использовать FastAPI с psycopg2 ?

@ВладимирТалалаев-н3р
9 days ago

SQLAlchemy 2.0 или 1.4 используете?

@flower-py
9 days ago

Здравствуйте! Спасибо за видео, но поделитесь, пожалуйста, ссылкой на репозиторий (если есть).

А то при запуске сервера возникает ошибка "Invalid argument(s) 'create_engine' sent to create_engine()", и я подозреваю, что где-то опечатался, но непонятно где.

20
0
Would love your thoughts, please comment.x
()
x