[FastAPI] Move Fast with FastAPI

brick·2022년 12월 30일
0
post-thumbnail

BaseModel

from pydantic import BaseModel

class Book(BaseModel):
    id: UUID
    title: str
    author: str
    description: Optional[str]
    rating: int


Post Request BaseModel

@app.post("/", status_code=status.HTTP_201_CREATED)
async def create_book(book: Book):
    BOOKS.append(book)
    return book


Data Validation

from pydantic import BaseModel, Field

class Book(BaseModel):
    id: UUID
    title: str = Field(min_length=1)
    author: str = Field(min_length=1, max_length=100)
    description: Optional[str] = Field(title="Description of the book",
                                       max_length=100,
                                       min_length=1)
    rating: int = Field(gt=-1,
                        lt=101)


BaseModel Configurations

class Book(BaseModel):
    id: UUID
    title: str = Field(min_length=1)
    author: str = Field(min_length=1, max_length=100)
    description: Optional[str] = Field(title="Description of the book",
                                       max_length=100,
                                       min_length=1)
    rating: int = Field(gt=-1,
                        lt=101)

    class Config:
        schema_extra = {
            "example": {
                "id": "178e4d55-888a-4100-9868-7a4ff5b19d5e",
                "title": "Computer Science Pro",
                "author": "Coding with bromp",
                "description": "A very nice description of a book",
                "rating": 75
            }
        }


Get Request

@app.get("/book/{book_id}")
async def read_book(book_id: UUID):
    for x in BOOKS:
        if x.id == book_id:
            return x
        
    raise raise_item_cannot_be_found_exception()
    
    
@app.get("/book/rating/{book_id}", response_model=BookNoRating)
async def read_book_no_rating(book_id: UUID):
    for x in BOOKS:
        if x.id == book_id:
            return x
    raise raise_item_cannot_be_found_exception()


Put Request

@app.put("/{book_id}")
async def update_book(book_id: UUID, book: Book):
    counter = 0

    for x in BOOKS:
        counter += 1
        if x.id == book_id:
            BOOKS[counter - 1] = book
            return BOOKS[counter - 1]
        
    raise raise_item_cannot_be_found_exception()


Delete Request

@app.delete("/{book_id}")
async def delete_book(book_id: UUID):
    counter = 0

    for x in BOOKS:
        counter += 1
        if x.id == book_id:
            del BOOKS[counter - 1]
            return f"ID: {book_id} deleted"

    raise raise_item_cannot_be_found_exception()

0개의 댓글