** How to access HTTP with Python **
This time, we will use the Requests library to handle the REST-style Web API.
Before we use it, let's take a brief look at HTTP methods / REST APIs. The type of request made from the client to the server is called a method, and there are basically the following eight types.
Method | Description |
---|---|
GET | Get resources |
HEAD | Get only HTTP headers for resources |
POST | Send data from client to server |
PUT | Save resources |
DELETE | Delete resource |
CONNECT | Establish a tunnel with the server |
OPTIONS | Find out which methods the server allows |
TRACE | Examine the network route to the server |
REST API is an API implementation that uses four HTTP methods "GET", "POST", "PUT", and "DELETE".
HTTP method | Behavior in REST |
---|---|
GET | Resource acquisition (READ) |
POST | Resource creation (CREATE) |
PUT | Resource update (UPDATE) |
DELETE | Delete resource (DELETE) |
Installation is done with pip.
pip install requests
Basically, it is OK if you specify the URL as follows (parameters are optional)
import requests
url = "http://xxxxx"
pyaload = {"key1":"value1", "key2":"value2"}
r = requests.get(url, params=payload)
The usage is the same except for GET.
r = requests.post(url)
r = requests.put(url)
r = requests.delete(url)
response
The response from the server can be confirmed as follows according to the response format.
#text
r.text
#binary
r.content
# JSON
r.json()
#Raw response
r.raw
#HTTP status code of the response
r.status_code
Try hitting this Zip Code Search API from Python.
import requests
url = "http://zip.cgis.biz/xml/zip.php"
payload = {"zn": "1310045"}
r = requests.get(url, params=payload)
r.text
Execution result
'<?xml version="1.0" encoding="utf-8" ?>\n<ZIP_result>\n<result name="ZipSearchXML" />\n<result version="1.01" />\n<result request_url="http%3A%2F%2Fzip.cgis.biz%2Fxml%2Fzip.php%3Fzn%3D1310045" />\n<result request_zip_num="1310045" />\n<result request_zip_version="none" />\n<result result_code="1" />\n<result result_zip_num="1310045" />\n<result result_zip_version="0" />\n<result result_values_count="1" />\n<ADDRESS_value>\n<value state_kana="Tokyo" />\n<value city_kana="Sumidaku" />\n<value address_kana="Ossiage" />\n<value company_kana="none" />\n<value state="Tokyo" />\n<value city="Sumida Ward" />\n<value address="Oshiage" />\n<value company="none" />\n</ADDRESS_value>\n</ZIP_result>\n'
Recommended Posts