from fastapi import FastAPI, Body
app = FastAPI()
BOOKS = [
{"title": "Title One", "author": "Author One", "category": "science"},
{"title": "Title Two", "author": "Author Two", "category": "science"},
{"title": "Title Three", "author": "Author Three", "category": "history"},
{"title": "Title Four", "author": "Author Four", "category": "math"},
{"title": "Title Five", "author": "Author Five", "category": "math"},
{"title": "Title Six", "author": "Author Two", "category": "math"},
]
@app.get("/")
async def first_api():
return {"message": "Fisrt FastAPI 페이지"}
@app.get("/books")
async def read_all_books():
return BOOKS
@app.get("/books_/{book_title}")
async def read_book(book_title: str):
for book in BOOKS:
if book.get("title").casefold() == book_title.casefold():
return book
return {"message": "Book not found"}
@app.get("/books/")
async def read_category_by_query(category: str):
return [book for book in BOOKS if book.get("category").casefold() == category.casefold()]
@app.get("/books/{book_author}")
async def read_author_category_by_query(book_author: str, category: str):
books_to_return = []
for book in BOOKS:
if book.get("author").casefold() == book_author.casefold() and \
book.get("category").casefold() == category.casefold():
books_to_return.append(book) # 해당 조건에 맞는 책을 리스트에 추가
return books_to_return
@app.post("/books/create_book")
async def create_book(new_book=Body()): # post 방식에서 Body()를 사용할 수 있음
BOOKS.append(new_book) # 새로운 책을 추가
@app.put("/books/update_book")
async def update_book(updated_book=Body()): # put 방식에서 Body()를 사용할 수 있음
for i in range(len(BOOKS)):
if BOOKS[i].get("title").casefold() == updated_book.get("title").casefold(): # casefold()를 사용하여 대소문자 구분을 없앰
BOOKS[i] = updated_book # 해당 책의 정보를 업데이트
@app.delete("/books/delete_book/{book_title}")
async def delete_book(book_title: str):
for i in range(len(BOOKS)):
if BOOKS[i].get("title").casefold() == book_title.casefold():
del BOOKS[i] # 해당 책을 삭제
# 특정 저자의 책을 반환하는 API
@app.get("/books/byauthor/{author}")
async def read_author_books(author: str):
books_to_return = []
for book in BOOKS:
if book.get("author").casefold() == author.casefold():
books_to_return.append(book)
return books_to_return