ソースに絡まるエスカルゴ

貧弱プログラマの外部記憶装置です。

【python】pythonを使ってGET/POST/PUTを行う

 今回はpythonを使ってGET/POST/PUTのそれぞれを行う方法です。

 また今回扱う方法はpython3系でのものになるので注意してください。

 では始めます。


1:GET/POST/PUTを行う記述
 それぞれ以下のように記述します。

・GET

import urllib.request

def url_get(url_str):
    try:
        res_code = None
        res_text = None
        # GET
        response = urllib.request.urlopen(url_str)
        res_code = response.getcode()
        html = response.read()
        res_text = html.decode('utf-8')
    except Exception as e :
        raise e
    finally:
        return res_code, res_text


・POST

import urllib.request
import json

def url_post(url_str, data_dict):
    try:
        res_code = None
        res_text = None
        # POST
        headers = {"Content-Type" : "application/json"} # json形式の場合必須
        data = json.dumps(data_dict).encode("utf-8")
        request = urllib.request.Request(url_str, data, method='POST', headers=headers)
        response = urllib.request.urlopen(request)
        res_code = response.getcode()
        html = response.read()
        res_text = html.decode('utf-8')
    except Exception as e :
        raise e
    finally:
        return res_code, res_text

・PUT

import urllib.request
import json

def url_put(url_str, data_dict):
    try:
        res_code = None
        res_text = None
        # PUT
        headers = {"Content-Type" : "application/json"} # json形式の場合必須
        data = json.dumps(data_dict).encode("utf-8")
        request = urllib.request.Request(url_str, data, method='PUT', headers=headers)
        response = urllib.request.urlopen(request)
        res_code = response.getcode()
        html = response.read()
        res_text = html.decode('utf-8')
    except Exception as e :
        raise e
    finally:
        return res_code, res_text

 読めば何となくわかるとは思いますが、GETの場合は「urllib.request.urlopen」関数を使って引数の結果を取得しています。存在しないURLなどエラーが発生した場合はExceptionがraiseされます(本当はtry exceptの範囲を狭めるべきだとは思いますが面倒なので全部を範囲にしてます…)。

 POSTとPUTの場合は「urllib.request.Request」関数でリクエストを作成してから「urllib.request.urlopen」関数を使っています。
 またこれら2つはヘッダーとして「{"Content-Type" : "application/json"}」を追加しており、これによりjson形式を送ることができます。json形式を送っているのにこのヘッダーを追加していなかった場合、jsonではなくjson文字列として送られてしまうので注意が必要です。


2:サンプルを動かす
 ではサンプルを動かしていきます。と言ってもPOSTとPUTは簡単に試せないので、今回はGETだけです。

・request_test.py

# -*- coding:utf-8 -*-
import urllib.request
import json

def main():
    get_code, get_text = url_get("https://www.google.com/")
    print(get_code)
    print(get_text)

    # POSTは適宜書き換えて試してください
    # post_data = {"test", "てすと"}
    # post_code, post_text = url_post("https://www.google.com/", post_data)
    # print(post_code)
    # print(post_text)

    # PUTは適宜書き換えて試してください
    # put_data = {"test", "てすと"}
    # put_code, put_text = url_put("https://www.google.com/", put_data)
    # print(put_code)
    # print(put_text)


def url_get(url_str):
    try:
        res_code = None
        res_text = None
        # GET
        response = urllib.request.urlopen(url_str)
        res_code = response.getcode()
        html = response.read()
        res_text = html.decode('utf-8')
    except Exception as e :
        raise e
    finally:
        return res_code, res_text


def url_post(url_str, data_dict):
    try:
        res_code = None
        res_text = None
        # POST
        headers = {"Content-Type" : "application/json"}
        data = json.dumps(data_dict).encode("utf-8")
        request = urllib.request.Request(url_str, data, method='POST', headers=headers)
        response = urllib.request.urlopen(request)
        res_code = response.getcode()
        html = response.read()
        res_text = html.decode('utf-8')
    except Exception as e :
        raise e
    finally:
        return res_code, res_text


def url_put(url_str, data_dict):
    try:
        res_code = None
        res_text = None
        # PUT
        headers = {"Content-Type" : "application/json"}
        data = json.dumps(data_dict).encode("utf-8")
        request = urllib.request.Request(url_str, data, method='PUT', headers=headers)
        response = urllib.request.urlopen(request)
        res_code = response.getcode()
        html = response.read()
        res_text = html.decode('utf-8')
    except Exception as e :
        raise e
    finally:
        return res_code, res_text


if __name__ == "__main__":
    main()


 以上がpythonを使ってGET/POST/PUTを行う方法です。

 pythonからAPIを呼び出したりする場合に使うことになると思います。

 またpython2系と3系両方で使える書き方もあり、その方法でGoogle検索の結果を取得している方もいるので色々と便利そうです。


・参考資料