Development

[flask] 서버와 클라이언트의 GET, POST API 설계

개발자 강정 2021. 12. 31. 16:59

서버 쪽의 app.py의 내용은 다음과 같다.

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

@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=5001,debug=True)

클라이언트에서는 GET과 POST의 방식으로 서버에 데이터를 요청하고, 응답을 받는다.

클라이언트 쪽에서는 ajax를 이용해서 데이터를 요청한다.

$.ajax({
    type: "GET",
    url: "/test?title_give=봄날은간다",
    data: {},
    success: function(response){
       console.log(response)
    }
  })

GET에서는 url을 통해 서버에 'title_give'라는 값을 보냈고, 서버로부터 response를 받는다.

$.ajax({
    type: "POST",
    url: "/test",
    data: { title_give:'봄날은간다' },
    success: function(response){
       console.log(response)
    }
  })

POST에서는 data를 보내고 response를 받는다.

 

API를 만들고 사용하는 순서는 다음과 같다.

  1. 클라이언트와 서버 확인하기
  2. 서버부터 만들기
  3. 클라이언트 만들기
  4. 완성 확인하기