Python: post request with json

ออกตัวล้อฟรีก่อนว่าผมเขียนภาษา dynamic อยู่ 2 ภาษาคือ พอจะเขียน python ได้บ้าง (งาน script เล็กๆ แทน shellscript หรือเขียน process log file เพื่อเสริมการทำงาน) และภาษา javascript ซึ่งใช้ทำงานจริงจังมา 2 ปี

ปลายปีที่แล้วมีงานที่ต้องลอง reproduce ปัญหาด้วยการยิง http post request ที่มี input เป็น json format เพื่อดูผลการทำงานของ server อยู่บ่อยๆ เลยต้องหาวิธียิง request แบบง่ายๆ ซึ่งคิดไว้ 3 ทางคือ

  • ใช้ jQuery.ajax เขียน ก็ใช้เวลาไม่นาน
  • ใช้ Advanced REST client plugin บน Chrome ก็ได้
  • ใช้ RESTClient ของ Firefox ก็ได้

แต่ทุกตัวต้องมาเปิด browser อะไรยุ่งยาก เลยหาวิธีเขียนบน python รันแค่ cmd แล้วรัน script ก็น่าจะได้ผลเร็วกว่าเปิด browser พวกนี้ ก็เลยไปค้นๆ google มา

วิธีแรกใช้ lib Requests

import requests
import json

payload={'service':'QUOTE','subject':'AAPL'}
url='http://1xx.xx.xxx.xxx:8080/quote'
headers = {'content-type': 'application/json'}
r = requests.post(url, data=json.dumps(payload), headers=headers)
print r.json

สิ่งที่ผมลืมไปคือหลังๆ ผมติด json บน javascript ที่ key ไม่จำเป็นต้องเป็น string ซึ่งมันขัดกับ dictionary ของ python เลยงงๆ อยู่สักพักก็ได้ http request แบบง่ายๆ ขึ้นมา script นึง

ไอ้ script ที่แล้วใช้ 3rd party lib เลยอยากลองแบบ python lib เพียวๆ ดูบ้าง ลองค้นๆ วิธีดูสักพักก็ได้เจ้าตัวนี้มา

import urllib2
import json

payload=json.dumps({'closure':'Python test tool','service':'Chart','subject':['AAPL']})
headers = {'content-type': 'application/json'}
req = urllib2.Request(url='http://1xx.xx.xxx.xxx:8080/chart',data=payload,headers=headers)
f=urllib2.urlopen(req)
print f.read()
f.close()

จะเห็นว่า code ยุ่งยากขึ้นอย่างเห็นได้ชัด แต่ก็ค่อนข้างจะ simple ตามสไตล์ python อยู่ดี

ป.ล. ผมเคยลองหาข้อมูล python call webservice (xml, soap พวกนั้น) เพื่อใช้ทำ script test แต่พบว่ามันยากเย็นแสนเข็ญจนตัดใจไปใช้ soapui แทน

2 thoughts on “Python: post request with json

  1. curl -vL -H “Content-Type: application/json” “http://1xx.xxx.xx.xx:8080/chart” -d “payload={‘closure’:’Python test tool’,’service’:’Chart’,’subject’:[‘AAPL’]}”

  2. รู้สึกว่า lib request สามารถใช้อย่างนี้ได้เลยนะครับ
    requests.post_json(url, data=payload)
    ถ้า header เป็นแค่ {‘content-type’: ‘application/json’} lib requests จะจัดการให้เองครับ ไม่ต้องใส่เพิ่ม แต่ไม่แน่ใจว่าใช้ได้ตั้งแต่เวอร์ชันไหน

Leave a reply to pittaya Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.