Requests-handling-post-put-patch-delete-requests

提供:Dev Guides
移動先:案内検索

POST、PUT、PATCH、DELETEリクエストの処理

この章では、リクエストライブラリを使用してPOSTメソッドを使用する方法と、URLにパラメータを渡す方法について説明します。

POSTを使う

PUTリクエストの場合、リクエストライブラリにはrequests.post()メソッドがあり、その例を以下に示します-

インポート要求

myurl = 'https://postman-echo.com/post'
myparams = {'name': 'ABC', 'email':'[email protected]'}
res = requests.post(myurl, data=myparams)
print(res.text)

出力

E:\prequests>python makeRequest.py
{"args":{},"data":"","files":{},"form":{"name":"ABC","email":"[email protected]"},
"headers":{"x-forwarded-proto":"https","host":"postman-echo.com","content-
length":"30","accept":"*/*","accept-encoding":"gzip,deflate","content-
type":"application/x-www-form-urlencoded","user-agent":"python-
requests/2.22.0","x-forwarded-
port":"443"},"json":{"name":"ABC","email":"[email protected]"},
"url":"https://postman-echo.com/post"}

上記の例では、フォームデータをキーと値のペアとして、requests.post()内のデータパラメータに渡すことができます。 また、リクエストモジュールでPUT、PATCH、DELETEを使用する方法についても説明します。

PUTの使用

PUTリクエストの場合、リクエストライブラリにはrequests.put()メソッドがあります。その例を以下に示します。

import requests
myurl = 'https://postman-echo.com/put'
myparams = {'name': 'ABC', 'email':'[email protected]'}
res = requests.put(myurl, data=myparams)
print(res.text)

出力

E:\prequests>python makeRequest.py
{"args":{},"data":"","files":{},"form":{"name":"ABC","email":"[email protected]"},
"headers":{"x-forwarded-proto":"https","host":"postman-echo.com","content-
length":
"30","accept":"*/*","accept-encoding":"gzip, deflate","content-
type":"applicatio
n/x-www-form-urlencoded","user-agent":"python-requests/2.22.0","x-forwarded-
port
":"443"},"json":{"name":"ABC","email":"[email protected]"},
"url":"https://postman-echo.com/put"}

PATCHの使用

PATCHリクエストの場合、リクエストライブラリにはrequests.patch()メソッドがあります。その例を以下に示します。

import requests
myurl = https://postman-echo.com/patch'
res = requests.patch(myurl, data="testing patch")
print(res.text)

出力

E:\prequests>python makeRequest.py
{"args":{},"data":{},"files":{},"form":{},"headers":{"x-forwarded-
proto":"https"
,"host":"postman-echo.com","content-length":"13","accept":"*/*","accept-
encoding
":"gzip, deflate","user-agent":"python-requests/2.22.0","x-forwarded-
port":"443"
},"json":null,"url":"https://postman-echo.com/patch"}

DELETEの使用

DELETEリクエストの場合、Requestsライブラリにはrequests.delete()メソッドがあります。その例を以下に示します。

import requests
myurl = 'https://postman-echo.com/delete'
res = requests.delete(myurl, data="testing delete")
print(res.text)

出力

E:\prequests>python makeRequest.py
{"args":{},"data":{},"files":{},"form":{},"headers":{"x-forwarded-
proto":"https"
,"host":"postman-echo.com","content-length":"14","accept":"*/*","accept-
encoding
":"gzip, deflate","user-agent":"python-requests/2.22.0","x-forwarded-
port":"443"
},"json":null,"url":"https://postman-echo.com/delete"}