안녕하세요 오늘은 FAST API의 get, post 사용방법에 대해 소개시켜 드리겠습니다
기본적인 설치 내용은 빼려고 했으나 다시 추가하기로 해서 넣어두겠습니닷
- FAST API 설치
pip install fastapi
pip install uvicorn
# 오늘 사용할 예정
pip install httpx
2. 기본적인 get 사용 방법
@app.get("/")
def main_re():
return 'hello youngs'
실행해보면 웹페이지에 hello youngs가 출력되는 코드입니다.
3. URL 리다이렉트
@app.get("/")
def main_re():
return RedirectResponse("http://127.0.0.1:8000/main/")
저는 루트 페이지가 메인이 아닐때 사용하는 URL 리다이렉트 방법입니다 들어올때는 URL이 적은게 복잡하지 않고 편리해 보이기에 사용할껄요? 다른분들은 어떻게 사용하는지 확인해 본적이 없습니닷
4. JSON 값을 리턴하기
# JSON 값을 리턴하는 API
@app.get("/items/", response_class=JSONResponse)
async def read_items():
return {"item_id": "Foo"}
JSON 값을 출력하기만 하는 코드입니다
5. JSON 값을 리턴하는 함수를 통해 값 요청하기
async def call_main():
async with httpx.AsyncClient() as client:
response = await client.get('http://127.0.0.1:8000/items/')
return response.json()
@app.get("/main/")
async def main_page(request: Request):
client_host = request.client.host
response_data = await call_main()
return {"client_host": client_host, "response_data": response_data} #, "response_cal": response_cal}
client의 http 주소 출력과 4번에서 만든 items의 JSON 값을 요청받는 함수를 통해 값을 요청하는 코드입니다
간단히 get API에 JSON형식 리턴값을 요청 및 응답받아 출력하는 방식입니다
6. get URL을 통해 값 받아오기
@app.get("/items/line/{item_id}")
async def get_line(item_id: int):
return item_id
조금 고전적이지만 쉽고 보안성이 보장되지 않는 방법인 get URL을 통한 값 받아오기 방법입니다
7. BaseModel로 값을 정의하고 값을 포함한 post 요청과 값에 대한 리턴을 출력하기
# 7-BaseModel : 값 정리역할
class Item(BaseModel):
price: int
cnt: int
name: str
# 7-response : post test 받은 값을 리턴
@app.post("/items_test/")
async def items_test(item: Item):
# dict_price = {"item_price": item.price, "item_cnt": item.cnt}
return item.price * item.cnt, item.name
# 7-requestpost : test json 값과 함께 post 요청
@app.get('/ii/')
async def read_item():
# POST 요청을 생성하여 /items_test 엔드포인트에 데이터 전송
async with httpx.AsyncClient() as client:
item_data = {"price": 10, "cnt": 5, "name":"youngs"} # 원하는 데이터 설정
try:
response = await client.post("http://127.0.0.1:8000/items_test/", json=item_data)
response.raise_for_status() # HTTP 오류가 있는 경우 예외 발생
return {"item_from_post": response.json()}
except httpx.HTTPError as e:
return {"error": f"HTTP error occurred: {str(e)}"}
except Exception as e:
return {"error": f"An error occurred: {str(e)}"}
BaseModel을 통해 데이터 유효성 검사를 하고 post items_test 에서 간단한 곱셈을 통해 기능을 부여한 후에 리턴하여 ii에서 받도록 하는 이제조금 API를 사용하는 형태의 구조입니다
get ii 쪽에 예외처리는 대부분 BaseModel에서 유효성 검사가 되지않는 경우를 위한 예외처리를 추가했습니다
오늘은 웹에서 아주 기본적으로 사용되는 get, post를 소개해보았습니다 이제 앞으로 restful을 간단히 정리해보고 필요한 API를 하나씩 구현해보면서 프로젝트를 완성해보도록 하겠습니다
프로젝트는 데이터 분석에서 사용한 네이버 API를 연동해서 자동화를 통한 데이터 수집 까지만 구상해서 만들어보도록 하겠습니다
데이터는 추후 어떻게 활용되는지 조금 더 생각해보고 Slack을 사용하여 알림을 주는 느낌으로 구상하고있습니다!
다음에는 아마 RESTFULL API 일것같습니다
마지막으로
공부에 사용한 코드 전체 올려드립니다!
import httpx
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from fastapi.responses import RedirectResponse
from pydantic import BaseModel
app = FastAPI()
# 2. 기본형
@app.get("/")
def main_re():
return 'hello youngs'
# 3. 루트 접속 시 main 으로 리다이렉트
@app.get("/")
def main_re():
return RedirectResponse("http://127.0.0.1:8000/main/")
# 4. JSON 값을 리턴하는 API
@app.get("/items/", response_class=JSONResponse)
async def read_items():
return {"item_id": "Foo"}
# 5-함수 : JSON 값을 리턴하는 API 값 call 함수
async def call_main():
async with httpx.AsyncClient() as client:
response = await client.get('http://127.0.0.1:8000/items/')
return response.json()
# 5-API : API Call 함수로 값 요청하기
@app.get("/main/")
async def main_page(request: Request):
client_host = request.client.host
response_data = await call_main()
return {"client_host": client_host, "response_data": response_data} #, "response_cal": response_cal}
# 6. get URL
@app.get("/items/line/{item_id}")
async def get_line(item_id: int):
return item_id
# 7-BaseModel : 값 정리역할
class Item(BaseModel):
price: int
cnt: int
name: str
# 7-response : post test 받은 값을 리턴
@app.post("/items_test/")
async def items_test(item: Item):
# dict_price = {"item_price": item.price, "item_cnt": item.cnt}
return item.price * item.cnt, item.name
# 7-requestpost : test json 값과 함께 post 요청
@app.get('/ii/')
async def read_item():
# POST 요청을 생성하여 /items_test 엔드포인트에 데이터 전송
async with httpx.AsyncClient() as client:
item_data = {"price": 10, "cnt": 5, "name":"youngs"} # 원하는 데이터 설정
try:
response = await client.post("http://127.0.0.1:8000/items_test/", json=item_data)
response.raise_for_status() # HTTP 오류가 있는 경우 예외 발생
return {"item_from_post": response.json()}
except httpx.HTTPError as e:
return {"error": f"HTTP error occurred: {str(e)}"}
except Exception as e:
return {"error": f"An error occurred: {str(e)}"}
'Python > FastAPI' 카테고리의 다른 글
Fast API 장단점 (0) | 2024.01.29 |
---|