지식이 늘었다/웹개발

FastAPI 기초 (1) GET과 Path Parameter

PurpleGuy101 2024. 12. 18. 10:03

 

0.

 

웹사이트는 백앤드서버에 HTTP Request 를 요청하며

서버는 Request에 대한 Action을 수행하고

Response를 만들어 웹사이트에 응답한다.

 

1.

백앤드서버나 데이터베이스가 표준적으로 갖추어야할 기능을

CRUD Operation이라고 하며, Create Read Update Delete의 Acronym이다.

 

HTTP request에서는 이러한 CRUD 기능을

Create -> POST

Read -> GET

Update -> PUT

Delete -> DELETE

과 같은 메소드로 대응시켜 사용한다.

 

2.

가장 기본이 되는 HTTP Method는 Read이다.

웹사이트의 내용물을 일단 받아서 읽는 작업이 선행되어야

웹사이트에 회원가입을 하거나, 게시글을 작성하거나, 게시글을 수정/삭제 할 수 있기 때문

 

그래서 서버가 GET method에 어떻게 대응하는지부터 배우는 것이 기초이다.

 

3.

 

#app1.py

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def first_api():
    return {'message' : 'Hello World!'}

 

uvicorn app1:app

 

127.0.0.1:8000/에 접속시 'message' : 'Hello World' 반환

 

4.

 

(https://fastapi.tiangolo.com/tutorial/path-params/)

 

fastapi에서는 Path Parameter를 string의 형태로 정의하고 동적인 경로를 설정해줄 수 있다.

 

from fastapi import FastAPI
app = FastAPI()

@app.get("/items/{item_id}")
async def read_item(item_id):
    return {"item_id": item_id}

 

 

5.

Dynamic Path를 이용한 GET method 예시

 

#book.py

from fastapi import FastAPI, HTTPException
app = FastAPI()
# uvicorn books:app --reload

@app.get("/api-endpoint")
async def first_api():
    return {'message' : 'Hello World!'}

@app.get("/books")
async def first_api():
    return BOOKS

BOOKS = [
    {'title': 'Title 1', 'author': 'Author 1', 'category':'science'},
    {'title': 'Title 2', 'author': 'Author 2', 'category':'math'},
    {'title': 'Title 3', 'author': 'Author 3', 'category': 'fantasy'},
    {'title': 'Title 4', 'author': 'Author 4', 'category':'novel'},
    {'title': 'Title 5', 'author': 'Author 5', 'category':'info'},
    {'title': 'Title 6', 'author': 'Author 6', 'category':'travel'},
]

@app.get("/books/{bookName}")
async def get_book_info(bookName: str):
    for book in BOOKS:
        if book['title'].lower() == bookName.lower():
            return book
    
    raise HTTPException(status_code=404, detail = "Book not found")

 

 

고정경로FixedPath와 동적경로DynamicPath가 존재할 경우

함수의 순서에 따라 다르게 실행될 수 있다.

가령 고정 경로로 "/books/myName"으로 엔드포인트를 설정해주었다면,

@app.get("books/myName")

async def read_user_myName 

의 함수가 

 

@app.get("/books/{bookName}")
async def get_book_info(bookName: str)

...

의 함수보다 먼저와야지 고정경로 myName에 대한 함수가 실행된다.