FastAPI is a modern web framework for building APIs with Python. It is easy to use, fast, and asynchronous, making it a great choice for developing web applications. In this tutorial, we will create a web application using FastAPI, Poetry, Pydantic V2, and APIRouter to implement CRUD operations.
To get started, make sure you have Python installed on your system. You can download and install Python from the official website. We will also be using Poetry as the package manager for our project. To install Poetry, run the following command in your terminal:
curl -sSL https://install.python-poetry.org | python3
Once Poetry is installed, create a new project directory and navigate to it in your terminal. Then, run the following command to create a new Poetry project:
poetry new fastapi-crud
This will create a new directory with the name fastapi-crud
containing the basic structure of a Python project. Navigate to the newly created directory and then add FastAPI and Pydantic V2 as dependencies to your project by running the following commands:
poetry add fastapi pydantic==1.8
Next, we will create a new Python file called main.py
in the fastapi-crud
directory. In this file, we will define our FastAPI application and set up our API routes using APIRouter. Here is an example of what the main.py
file might look like:
from fastapi import FastAPI, APIRouter
from pydantic import BaseModel
app = FastAPI()
router = APIRouter()
class Item(BaseModel):
name: str
description: str
items = []
@router.get("/items")
async def get_items():
return items
@router.post("/items")
async def create_item(item: Item):
items.append(item.dict())
return item
app.include_router(router)
In this example, we defined a simple FastAPI application with two API routes: one for getting all items and one for creating a new item. We also defined a Pydantic model called Item
to represent our items with name
and description
fields.
To run our FastAPI application, we need to start the uvicorn server. First, install uvicorn by running the following command:
poetry add uvicorn
Then, start the uvicorn server with the following command:
poetry run uvicorn main:app --reload
This will start the uvicorn server and run our FastAPI application. You can now access your API endpoints by navigating to http://127.0.0.1:8000
in your web browser.
In this tutorial, we covered the basics of creating a web application with FastAPI, Poetry, Pydantic V2, and APIRouter. This is just a starting point, and there is much more you can do with FastAPI to build powerful and efficient web applications. I recommend exploring the FastAPI documentation to learn more about the features and capabilities of this amazing web framework.
Этот плейлист- титанический труд,
браво!
я как то не особо понял зачем Poetry вообще. Ещё пример этот про приход нового сотрудника, а надо, чтобы у него были определенные зависимости на проекте. Дак мы же для этого и делали файлик с зависимости requirements через pip freeze. и в Гит мы этот файл также пушим всегда. И потом все остальные просто одной командой берут и ставят себе всё уже нужных версий, т.к. всё прописано в req
хороший урок, спасибо
Превосходная подача материала! Всё подробно и в то же время ничего лишнего. Преподавать ваше призвание! Спасибо за курс.
а в продакшне для endpoint'ов, которые ведут за собой crud операции на создание чего-либо, лучше указывать статус ответа 200 или 201?
после того как сделал poetry sync а потом ввёл команду poetry show –tree
показывает это
Traceback (most recent call last):
File "<frozen runpy>", line 198, in _run_module_as_main
File "<frozen runpy>", line 88, in _run_code
File "C:UsersUserPycharmProjectsFastAPI_SurenvenvScriptspoetry.exe__main__.py", line 4, in <module>
ModuleNotFoundError: No module named 'poetry.console'
в чём может быть проблема?
добрый день а подскажите что за плагины стоят для терминала pycharm
весьма странно, что на англо и русс ресурсах нет никого кто бы так детально объяснил как это все переплетается и работает, находил и платные курсы, они уже неактуальны, спасибо за огромный труд! успехов
Спасибо большое за урок!
Отличный ролик, задумался вернуться в Пайтон и проект построить на ФастАпи, а не на Нест
в имени видео написано, что это первое видео, однако автор упоминает о каком-то предыдущем видео
'charmap' codec can't decode byte 0x98 in position 17: character maps to <undefined> – у меня вот такая ошибка при попытке сделать что-то с poetry
после poetry install –sync у меня поетри удалил сам себя, лол. Качаю щас заново
сложно когда твой уровень "world("hello print")" но я не сдаюсь и пока ничего не крашится)
Очень подробное, а главное понятное объяснение. Смотрел на других каналах, понимал, через слово, здесь все очень легко усваивается!
Было бы удобно, если бы ты распилил каждое видео по бранчам на гитхабе. Может в будущем попробуешь)
Все четко и по делу! 👍👍👍
Вначале сам себе проблему создал запустив pip freeze 🙂
Классно и четко объясняешь – быстро, без воды и всё по делу ! Видно, что готовился к записи и заморачивался с подрезкой видео 👍 странно что на канале так мало просмотров, годный проработанный контент
Хорошее видео, годное.