Python Flask 에서 Resource 클래스를 이용한 API 서버 개발 방법
수업중에 배운 Recipe 에서
예제를 간단히 정리해 보았습니다.
1. 라이브러리 설치
pip install flask
pip install flask-restful
2. API 서버 개발 간단 예제
app.py
# 라이브러리 호출
from flask import Flask
from flask_restful import Api
from resources.recipe import RecipeListResource
from resources.recipe_info import RecipeResource
# API 서버를 구축하기 위한 기본 구조
app = Flask(__name__)
# restfulAPI 생성
api = Api(app)
# 경로와 리소스(api코드) 연결
api.add_resource(RecipeListResource, '/recipes') # 목록 보기
api.add_resource(RecipeResource, '/recipes/<int:recipe_id>') # 특정 값 불러오기
if __name__ == '__main__' :
app.run()
API 서버를 구축하기 위한
기본 구조는~
app = Flashk(__name__)
... <code> ...
if__name__ = '__main__' :
app.run()
가운데 코드 부분에는
경로와 리소스(api 코드) 연결을
위한 경로를 적어줘야 합니다.
api.add_resource.RecipeListResource '/recipes'
api.add_resource.RecipeResource '/recipes/<int:recipe_id>')
recipe.py
# 라이브러리 호출
from flask_restful import Resource
# API를 만들기 위한 클래스 작성
# 클래스 : 변수와 함수로 구성된 묶음
# 클래스는 상속이 가능
# API를 만들기 위한 클래스는
# flask_restful 라이브러리의
# Resource class를 상속해서 생성하여야 함
class RecipeListResource(Resource) :
def post(self) :
# api 실행 코드를 여기에 작성
# 클라이언트에서 body 부분에 작성한 json을 받아오는 코드
data = request.get_json()
... <중략> ...
def get(self) :
# 쿼리 스트링으로 오는 데이터는 아래처럼 처리해준다.
offset = request.args.get('offset')
limit = request.args.get('limit')
... <중략> ...
API를 만들기 위한 클래스는 flask_restful
라이브러리의 Resource class를
상속해서 생성해야 합니다.
class RecipeListResource(Resource) :
recipe_info.py
# 라이브러리 호출
from flask_restful import Resource
# Resource 클래스를 상속받아 사용한다.
class RecipeResource(Resource) :
# 클라이언트로부터 /recipes/3 이런식으로 경리를 처리하므로
# 숫자는 바뀌므로 변수로 처리해준다.
def get(self, recipe_id) :
# DB에서 recipe_id에 들어있는 값에 해당되는 데이터를 셀렉트 해온다.
... <중략> ...
# 데이터를 업데이트하는 API들은 put 함수를 사용한다.
def put(self, recipe_id) :
# body에서 전달 된 데이터를 처리
data = request.get_json()
... <중략> ...
# 데이터를 삭제하는 API들은 delete 함수를 사용한다.
def delete(self, recipe_id) :
# body에서 전달 된 데이터를 처리
data = request.get_json()
... <중략> ...
힐링아무의 코딩일기 힐코딩!!
'Back End > API' 카테고리의 다른 글
API/ Serverless Framework 를 이용한 Github 코드를 AWS에 배포하기(CI/CD) (0) | 2022.06.29 |
---|---|
boto3 로 아마존 AWS의 버킷 s3 파일 업로드 (0) | 2022.06.24 |
API/ 포스트맨(POSTMAN)으로 API 테스트 사용법 (0) | 2022.06.17 |
댓글