Develop/FastAPI
FastAPI Path / Query Parameters 정리 - 12
김잠봉
2022. 12. 22. 09:42
728x90
1. Path Parameters
- url 경로에 들어가는 변수
- book_name이 경로 매개변수
@app.delete("/{book_name}")
async def delete_book(book_name):
del BOOKS[book_name]
return f"Book {book_name} deleted."


2. Query Parameters
- url 구문 제일 뒤에 "/" 붙혀도 되고 안붙혀도 됨
- ?(매개변수 값)와 &(추가 값)로 구분
@app.delete("/assignment/")
async def delete_book_assignment(book_name: str):
del BOOKS[book_name]
return BOOKS


3. Path / Query Parameter 종합
@app.get("/{apple}") # Path Parameter
async def test(apple):
return f"{apple} good"
@app.get("/apple") # Query Parameter
async def test(apple):
return f"{apple} good"
@app.get("/{fruit}") # Query Parameter
async def test(apple):
return f"{apple} good"
4. 선택적 쿼리 매개변수
- Default값이 None임으로 전체리스트 return or 선택 값만 return
@app.get("/")
async def read_all_books(skip_book: Optional[str] = None):
if skip_book:
new_books = BOOKS.copy()
del new_books[skip_book]
return new_books
return BOOKS



5. 필수 쿼리 매개변수
- url에도 반드시 매개변수값을 설정해줘야한다.
@app.get("/books/{book_name}")
async def read_book(book_name: str, book_id: str):
return f"{BOOKS[book_name+book_id]}"



5. 에러사항 확인
728x90
SMALL