本篇文章將帶大家如何使用 curl、Python、Postman 來 Request API (GET 與 POST),以下將帶幾個範例跟大家說明:
GET
GET Request URL: http://www.example.com Parameters: bookname, publisher
GET – 使用 curl
curl http://www.example.com?bookname=Mark&publisher=xyz
如輸出的格式為 JSON 要改成 Pretty Print 顯示可再指令後再 Pipes python -mjson.tool (更多方法可參考此篇說明)。
curl http://www.example.com?bookname=Mark&publisher=xyz | python -mjson.tool
若有回傳的值要將 UTF-8 顯示成中文字,則再 Pipes native2ascii -encoding UTF-8 -reverse,指令如下所示:
curl http://www.example.com?bookname=Mark&publisher=xyz | native2ascii -encoding UTF-8 -reverse
GET – 使用 Python 的 requests
import requests payload = {'bookname':'Mark','publisher':'xyz'} response = request.get("http://example.com", params=payload)
或是直接將參數串好再呼叫也可以,程式碼如下所示:
response = requests.get("http://www.example.com?bookname=Mark&publisher=xyz")
如回應的資料格式為 JSON,我們可以呼叫 json() 函示將回傳的資料轉成 dictionary 資料型態,
response_dic = response.json()
若只要文字字串則直接取出 text 值,程式碼如下所示:
response_text = response.text
GET – 使用 Postman
POST
POST Request URL: http://www.example.com/login.php Parameters: username, passwd
POST – 使用 curl
curl -d "username=markchang&passwd=12345" "http://www.example.com/login.php"
POST – 使用 Python 的 requests
import requests data = {'username':'markchang', 'passwd':'12345'} response = requests.post('http://example.com/login.php', data)
POST – 使用 Postman
參考文章:
1. HTTP Methods for RESTful Services
讚哦!
讚Liked by 1 person
“GET – 使用 Python 的 requests"
Line 4: response = request.get(“http://example.com", params=payload)
‘request’ 少一個 ‘s’
讚Liked by 1 person