본문 바로가기

웹 개발강의/파이썬 웹개발

[파이썬 웹개발] 4_2_GET,POST방식 API만들기

GET, POST 개념

👉 은행의 창구가 API와 같다는 것을 기억하시나요?
같은 예금 창구에서도 개인 고객이냐 기업 고객이냐에 따라 처리하는 것이 다른 것처럼

클라이언트가 요청 할 때에도, "방식"이 존재합니다.
HTTP 라는 통신 규약을 따른다는 거 잊지 않으셨죠? 클라이언트는 요청할 때 HTTP request method(요청 메소드)를 통해, 어떤 요청 종류인지 응답하는 서버 쪽에 정보를 알려주는 거에요. 

👉 GET, POST 방식

여러 방식(링크)이 존재하지만 우리는 가장 많이 쓰이는 GET, POST 방식에 대해 다루겠습니다.


- GET
  → 통상적으로! 데이터 조회(Read)를 요청할 때 예) 영화 목록 조회
  → 데이터 전달 : URL 뒤에 물음표를 붙여 key=value로 전달
   예) google.com?q=북극곰


- POST
  → 통상적으로! 데이터 생성(Create), 변경(Update), 삭제(Delete) 요청 할 때
   예) 회원가입, 회원탈퇴, 비밀번호 수정
  → 데이터 전달 : 바로 보이지 않는 HTML body에 key:value 형태로 전달

 

1. GET, POST요청 API 코드

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!'})

@app.route('/mypage')
def mypage():
   return '<button>나는 버튼이다</button>'

if __name__ == '__main__':
   app.run('0.0.0.0',port=5000,debug=True)

 

2. GET, POST요청 확인 Ajax코드

1) GET요청 확인

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

 

2) POST요청 확인

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