Develop/FastAPI

FastAPI Project Assignment - 29

동석해요 2022. 12. 26. 00:30
728x90
SMALL
인증해서 읽고 싶은 책 가져오는 것이 목표(연습하기)

1. async def book_login API 생성
2. username / password는 헤더를 사용해서 query parameter로 받는다.(username: FastAPIUser, password: test1234!)
3. username / password가 맞지 않는 경우 "Invalid User"을 반환한다.

1. 전체 코드

from typing import Optional
from fastapi import FastAPI, Header
from pydantic import BaseModel, Field
from uuid import UUID


app = FastAPI()


@app.post("/books/login")
async def book_login(book_id: int, username: Optional[str] = Header(None), password: Optional[str] = Header(None)):
    if username == 'FastAPIUser' and password == "test1234!":
        return BOOKS[book_id]
    return "Invalid User"


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": "637d1b93-0174-48e7-8959-e17530b6c690",
                "title": "Computer Science Pro",
                "author": "Codingwithroby",
                "description": "A very nice description of a book",
                "rating": 75
            }
        }


BOOKS = []


@app.get("/")
async def read_all_books(books_to_return: Optional[int] = None):

    if len(BOOKS) < 1:
        create_books_no_api()

    if books_to_return and len(BOOKS) >= books_to_return > 0:
        i = 1
        new_books = []
        while i <= books_to_return:
            new_books.append(BOOKS[i - 1])
            i += 1
        return new_books
    return BOOKS


def create_books_no_api():
    book_1 = Book(id="db6d5c1f-0460-4bab-8aa1-a801bf843273",
                  title="Title 1",
                  author="Author 1",
                  description="Description 1",
                  rating=75)
    book_2 = Book(id="4991c5f5-1097-404b-9825-4350a36fce96",
                  title="Title 2",
                  author="Author 2",
                  description="Description 2",
                  rating=60)
    book_3 = Book(id="5981f2bf-d135-451b-80da-fd8f9d591b6c",
                  title="Title 3",
                  author="Author 3",
                  description="Description 3",
                  rating=60)
    book_4 = Book(id="cdbd03e4-06af-4df8-aebc-4d52af51b5d5",
                  title="Title 4",
                  author="Author 4",
                  description="Description 4",
                  rating=60)
    BOOKS.append(book_1)
    BOOKS.append(book_2)
    BOOKS.append(book_3)
    BOOKS.append(book_4)

 

2. Swagger 확인

  • 왼쪽: 인증 성공
  • 오른쪽: 유효하지 않은 사용자로 인한 인증 실패

위 로직은 일반 텍스트를 통해 사용자 이름과 암호를 보내고 있기 때문에 좋은 인증이 아님
728x90
SMALL