본문 바로가기

python request로 API 호출

기존에 spring + kotlin으로 만들었던 API 서버에 python으로 API요청을 보내는 방법을 포스팅한다.

Request

python 내장 라이브러리에는 request라는 라이브러리가 있는데, 기본적으로 http , https에 대한 통신이 모두 구현 되어 있다.

사용 방법은 다음과 같다.

import requests

response =  requests.get(url , ...)
response =  requests.post(url, ...)
response =  requests.patch(url, ...)
response =  requests.put(url, ...)
response =  requests.delete(url ...)

여기서 API요청에 대해 크게 2가지 경우로 에러처리를 하면 된다.

  1. request 자체적으로 error가 났을 때 (인터넷 연결 문제 같은 경우)
  2. request는 잘 작동했으나 서버가 200번대 state가 아닌 다른 state 줬을 때

이에 대해서 에러 처리를 하면 다음과 같다.

import requests

try:
    response = requests.get(url) #다른 메소드도 똑같이
except requests.JSONDecodeError: #get은 에초에 decode할 일이 없어서 안해도 된다.
    print('data json decode error')
except requests.ConnectionError: 
    print('Network error')
except requests.RequestException:
    print('Request error')
finally:
    if response.status_code != 200:
        print('error')

위를 토대로 기존 API서버에 요청을 보내는 코드를 작성하면 다음과 같다.

import requests

try:
    response = requests.get("<https://study.lachani.com/v1/devices>")
except requests.JSONDecodeError:
    print('data json decode error')
except requests.ConnectionError: 
    print('Network error')
except requests.RequestException:
    print('Request error')
finally:
    if response.status_code != 200:
        print('error')
    print(response.text)

try:
    response = requests.post("<https://study.lachani.com/v1/devices>")
except requests.JSONDecodeError:
    print('data json decode error')
except requests.ConnectionError: 
    print('Network error')
except requests.RequestException:
    print('Request error')
finally:
    if response.status_code != 200:
        print('error')
    print(response.text)

try:
    response = requests.patch("<https://study.lachani.com/v1/devices/1/value>", 
    headers={
        "Content-type": "application/json"
    },
    data="request")
except requests.JSONDecodeError:
    print('data json decode error')
except requests.ConnectionError: 
    print('Network error')
except requests.RequestException:
    print('Request error')
finally:
    if response.status_code != 200:
        print('error')
    print(response.text)

try:
    response = requests.patch("<https://study.lachani.com/v1/devices/1/command>", 
    headers={
        "Content-type": "application/json"
    },
    data="open")
except requests.JSONDecodeError:
    print('data json decode error')
except requests.ConnectionError: 
    print('Network error')
except requests.RequestException:
    print('Request error')
finally:
    if response.status_code != 200:
        print('error')
    print(response.text)

*** 함수로 하면 좀 짧을 텐데 귀찮았다.***

그러면 다음과 같이 잘 반영 돼 있는 걸 확인 할 수 있다.