Develop/FastAPI

FastAPI Path Parameters(추가) - 07

김잠봉 2022. 12. 21. 14:55
728x90

1. dictionary 정의

BOOKS = {
    'book_1': {'title':'Title One','author':'Author One'},
    'book_2': {'title':'Title Two','author':'Author Two'},
    'book_3': {'title': 'Title Three', 'author': 'Author Three'},
    'book_4': {'title': 'Title Four', 'author': 'Author Four'},
    'book_5': {'title': 'Title Five', 'author': 'Author Five'},
}

 

2. 함수 정의

  • 전체 BOOKS의 list를 볼 수 있음
@app.get("/")
async def read_all_books():
    return BOOKS
  • BOOKS의 1개의 키 값이 무조건 들어가야함
  • read_book의 매개변수에는 string만 들어갈 수 있음
@app.get("/{book_name}")
async def read_book(book_name: str):
    return BOOKS[book_name]
  • dictionary에 없는 키 값을 입력 시 에러
 
728x90
SMALL