개발일지/웹개발

Flask 시작하기 - API 만들기

E-room 2022. 7. 6. 23:32
728x90

은행을 예로

같은 예금 창구에서도 개인 고객이냐 기업 고객이냐에 따라 처리하는 것이 다른 것처럼,

클라이언트가 요청 할 때에도, "방식"이 존재한다.

클라이언트는 요청할 때 HTTP request method를 통해서 응답하는 서버에 어떤 종류의 요청인지 알려준다.

 

 

GET, POST 방식 (더있음)

 

GET - 통상적으로 데이터 조회(Read)를 요청할 때 ex) 영화 목록 조회

         - 데이터 전달 : url 뒤에 물음표를 붙여 key=value로 전달 ex) google.com?q=북극곰

 

POST - 통상적으로 데이터 생성(Create), 변경(Update), 삭제(Delete) ex) 회원가입, 회원탈퇴, 비밀번호 수정

           - 데이터 전달 : 바로 보이지 앟는 HTML body에 key:value 형태로 전달

 

 

 

 

GET 방식으로 요청해보기

이전 글의 코드에 아래 코드들을 붙여 넣고 request 함수와 jsonify 함수를 사용해야하므로 상단 import 목록에 추가한다.

더보기

GET 요청 확인 Ajax코드

$.ajax({
    type: "GET",
    url: "/test?title_give=봄날은간다",
    data: {}, /*data를 받으러 가기 때문에 비워둔다*/
    success: function(response){
       console.log(response)
    }
  })

GET요청 API 코드

@app.route('/test', methods=['GET'])
def test_get():
   title_receive = request.args.get('title_give')
   print(title_receive)
   return jsonify({'result':'success', 'msg': '이 요청은 GET!'})

 

 

서버를 실행하고 접속한 뒤

버튼을 누르면

파이썬 창
크롬 콘솔 창

html => 버튼누르기 => hey() 실행 => hey()안의 ajax코드 실행 => GET방식의 /test 창구로 찾아감 => title_give라는 이름으로 '봄날은간다'를 가져간다 => print()에 의해 '봄날은간다'를 찍어줌 => return인 jsonfiy값을 html의 response에 전달 => console.log(response)실행

 

 

POST방식으로 요청해보기

앞의 방식처럼 버튼을 하나더 만들고 아래코드들을 넣는다.

더보기
$.ajax({
    type: "POST",
    url: "/test",
    data: { title_give:'봄날은간다' }, /*전달해줄 data를 입력해준다*/
    success: function(response){
       console.log(response)
    }
  })
@app.route('/test', methods=['POST'])
def test_post():
   title_receive = request.form['title_give']
   print(title_receive)
   return jsonify({'result':'success', 'msg': '이 요청은 POST!'})

 

 

 

서버를 실행하고 접속한 뒤

버튼을 누르면

파이썬 창  (print가 더 밑에 있다)

 

크롬 콘솔 창

html => 버튼누르기 => hey2() 실행 => hey2()안의 ajax코드 실행 => POST방식의 /test 창구로 찾아감 => title_give에 data('봄날은간다') 를 전달 => print()에 의해 '봄날은간다'를 찍어줌 => return인 jsonfiy값을 html의 response에 전달 => console.log(response)실행

 

더보기

완성 예시

from flask import Flask, render_template, request, jsonify
app = Flask(__name__)

## URL 별로 함수명이 같거나,
## route('/') 등의 주소가 같으면 안됩니다.

@app.route('/')
def home():
   return render_template('index.html')

@app.route('/test', methods=['GET'])
def test_get():
   title_receive = request.args.get('title_give')
   print(title_receive)
   return jsonify({'result':'success', 'msg': '이 요청은 GET!'})

@app.route('/test', methods=['POST'])
def test_post():
   title_receive = request.form['title_give']
   print(title_receive)
   return jsonify({'result':'success', 'msg': '이 요청은 POST!'})

if __name__ == '__main__':
   app.run('0.0.0.0', port=5000, debug=True)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <title>Document</title>

    <script>
        function hey() {
            $.ajax({
                type: "GET",
                url: "/test?title_give=봄날은간다",
                data: {}, /*data를 받으러 가기 때문에 비워둔다*/
                success: function (response) {
                    console.log(response)
                }
            })
        }

        function hey2() {
            $.ajax({
                type: "POST",
                url: "/test",
                data: {title_give: '봄날은간다'}, /*전달해줄 data를 입력해준다*/
                success: function (response) {
                    console.log(response)
                }
            })
        }
    </script>
</head>
<body>
    <button onclick="hey()">나는 GET 버튼!</button>
    <button onclick="hey2()">나는 POST 버튼!</button>
</body>
</html>

 

728x90