Python에서 rest api 호출하기 샘플 코드

* urllib2를 사용하여 [사용자 정보 요청] 호출

import urllib2

API_HOST = 'https://kapi.kakao.com'
APP_KEY = 'Bearer  [YOUR_ACCESS_TOKEN]'
data = {}

def req(path, query, method, data={}):
    url = API_HOST + path
    print('HTTP Method: %s' % method)
    print('Request URL: %s' % url)
    print('QueryString: %s' % query)
    if 'GET' == method:
        req = urllib2.Request(API_HOST + path)
    elif 'POST' == method:
        req = urllib2.Request(API_HOST + path, data)
    req.add_header('Authorization', APP_KEY)
    return urllib2.urlopen(req)

res = req('/v1/user/me', '', 'POST')

print("response status:\n%d" % res.getcode())
print("response info:\n%s" % res.info())
print("response body:\n%s" % res.read())

* requests를 사용하여 [사용자 정보 요청] 호출

import requests

API_HOST = 'https://kapi.kakao.com'
headers = {'Authorization': 'Bearer [YOUR_ACCESS_TOKEN]'}

def req(path, query, method, data={}):
    url = API_HOST + path
    print('HTTP Method: %s' % method)
    print('Request URL: %s' % url)
    print('Headers: %s' % headers)
    print('QueryString: %s' % query)

    if method == 'GET':
        return requests.get(url, headers=headers)
    else:
        return requests.post(url, headers=headers, data=data)

resp = req('/v1/user/me', '', 'GET')
print("response status:\n%d" % resp.status_code)
print("response headers:\n%s" % resp.headers)
print("response body:\n%s" % resp.text)

* requests를 사용하여 [나에게 보내기] 호출

import requests

API_HOST = 'https://kapi.kakao.com'
headers = {'Authorization': 'Bearer [YOUR_ACCESS_TOKEN]'}
data = {}

def req(path, query, method, data={}):
    url = API_HOST + path

    print('HTTP Method: %s' % method)
    print('Request URL: %s' % url)
    print('Headers: %s' % headers)
    print('QueryString: %s' % query)

    if method == 'GET':
        return requests.get(url, headers=headers)
    else:
        return requests.post(url, headers=headers, data=data)

template_id = 0 # 메시지 템플릿 v2의 아이디
params = {"template_id": {template_id}, "templates_args":{"name":"홍길동"}}
resp = req('/v2/api/talk/memo/send', '', 'POST', params)
print("response status:\n%d" % resp.status_code)
print("response headers:\n%s" % resp.headers)
print("response body:\n%s" % resp.text)