from fastapi import FastAPI
from routing.books import router as books_routing
app = FastAPI(openapi_url="/core/openapi.json", docs_url="/core/docs")
app.include_router(books_routing)
from datetime import datetime
from pydantic import BaseModel
class Author(BaseModel):
first_name: str
last_name: str
date_birth: datetime
biography: str
class Book(BaseModel):
title: str
annotation: str
date_publishing: datetime
author: Author
from typing import List
from schemas.books import Book
class BookRepository:
def get_books(self) -> List[Book]:
...
def create_book(self) -> Book:
...
from typing import List
from repositories.books import BookRepository
from schemas.books import Book
class BookBookService:
def __init__(self, repository: BookRepository) -> None:
self.repository = repository
def get_books(self) -> List[Book]:
result = self.repository.get_books()
return result
def create_book(self) -> Book:
result = self.repository.create_book()
return result
from repositories.books import BookRepository
from services.books import BookService
# repository - работа с БД
book_repository = BookRepository()
# service - слой UseCase
book_service = BookService(book_repository)
def get_book_service() -> BookService:
return book_service
В папке routing, создадим привычный нам файл books и реализуем обработчики запросов:
from typing import List
from fastapi import APIRouter, Depends
from depends import get_book_service
from schemas.books import Book
from services.books import BookService
router = APIRouter(prefix="/books", tags=["books"])
@router.get(
"",
responses={400: {"description": "Bad request"}},
response_model=List[Book],
description="Получение листинга всех книг",
)
async def get_all_books(
book_service: BookService = Depends(get_book_service),
) -> List[Book]:
books = book_service.get_books()
return books
@router.post(
"",
responses={400: {"description": "Bad request"}},
response_model=Book,
description="Создание книги",
)
async def get_all_books(
book_service: BookService = Depends(get_book_service),
) -> Book:
book = book_service.create_book()
return book