POST json with Python3 script

You often want to POST json with a little Python3 script (appropriate).

First, sample code.

import urllib.request, json

if __name__ == '__main__':
    url = "http://xxxx/xxxx" 
    method = "POST"
    headers = {"Content-Type" : "application/json"}

    #Convert Python objects to JSON
    obj = {"xxx" : "xxxx", 123 : 123} 
    json_data = json.dumps(obj).encode("utf-8")

    #Prepare http request and POST
    request = urllib.request.Request(url, data=json_data, method=method, headers=headers)
    with urllib.request.urlopen(request) as response:
        response_body = response.read().decode("utf-8")

Next, as a simple example, use "Nico Nico Douga" Snapshot Search API "" to play back the search results of "Yuzuki Yukari". I would like to get 30 videos with a large number.

import urllib.request, json

if __name__ == '__main__':
    url = "http://api.search.nicovideo.jp/api/snapshot/"
    method = "POST"
    obj = {
        "query" : "Yuitsuki Yukari",
        "service" : ["video"],
        "search" : ["title", "description", "tags"],
        "join" : ["title", "view_counter"],
        "sort_by" : "view_counter",
        "order" : "desc",
        "size" : 30,
        "issuer" : "xxxxxxxxxxxxxxxxxxxxx"
    }
    json_data = json.dumps(obj).encode("utf-8")
    headers = {"Content-Type" : "application/json"}

    request = urllib.request.Request(url, data=json_data, headers=headers, method=method)
    with urllib.request.urlopen(request) as response:
        response_body = response.read().decode("utf-8")
        
        result_objs = json.loads(response_body.split('\n')[0])
        for result_obj in result_objs["values"]:
            print("{0:<10}{1}".format(result_obj["view_counter"], result_obj["title"]))

#2903887 [Hatsune Miku] This is the Happiness and Security Committee. 【original】
#2331059 Mi-w-na-w-gi-w-w-ki-w-www (Shinobue withdrawal symptom L5)
#1979283 [Minecraft] Guerrilla craft Build a line of defense around and lay mines around#1
#1896978 [Minecraft] Guerrilla Craft Build a line of defense around you and lay mines around#5
#1805589 [Minecraft] Yukari "Let's blow up the Mage Tower" part1 [VOICEROID+The real condition]
#1662622 [Yuzuki Yukari] I had a monster without a name sung [PSYCHO-PASS】
#1617931 [Minecraft] Guerrilla Craft Build a line of defense around you and lay mines around#3
#1587257 [Hatsune Miku] I found a way to be happy forever. 【original】
#1531263 [Yuzuki Yukari] There seems to be a hidden command that makes you happy [Original]
#1499237 [Minecraft] Guerrilla Craft Build a line of defense around you and lay mines around#2
#1424024 [Yuzuki Yukari] Churrilla Churrilla Daddadda!
#1391173 [Minecraft] Guerrilla Craft Build a line of defense around you and lay mines around#7
#1356847 [Minecraft] Guerrilla Craft Build a line of defense around you and lay mines around#6
#1354592 [Minecraft] Yukari "Let's blow up the Mage Tower" part3 [VOICEROID+The real condition]
#1261669 [Minecraft] Yukari "Let's blow up the Mage Tower" part2 [VOICEROID+The real condition]
#1241053 [Minecraft] Guerrilla Craft Build a line of defense around you and lay mines around#8
#1223469 [Minecraft] Guerrilla Craft Build a line of defense around you and lay mines around#4
#1201715 [Minecraft] Yukari "Let's blow up the Mage Tower" part4 [VOICEROID+The real condition]
#1182955 [Minecraft] Guerrilla Craft Build a line of defense around and lay mines around#9
#1177519 [Minecraft] Yukari "Let's blow up the Mage Tower" part9 [VOICEROID+The real condition]
#1069852 [MAYU] A little happiness that I want to bring to fruition. 【original】
#1045793 [Minecraft] Guerrilla Craft Build a line of defense around and lay mines around ⑩
#1040149 [Minecraft] Yukari "Let's blow up the Mage Tower" part5 [VOICEROID+The real condition]
#1008825 [Minecraft] Yukari "Let's blow up the Mage Tower" part6 [VOICEROID+The real condition]
#993675 [Yuzuki Yukari] Goodbye Chain Saw
#963262 [Minecraft] Yukari "Let's blow up the Mage Tower" part7 [VOICEROID+The real condition]
#927444 [Minecraft] Yukari "Let's blow up the Mage Tower" part8 [VOICEROID+The real condition]
#895328 [Minecraft] Guerrilla Craft Build a line of defense around you and spread land mines ⑫
#892567 [Minecraft] Yukari "Let's blow up the Mage Tower" final episode [VOICEROID+The real condition]
#878046 [Minecraft] Guerrilla Craft Build a line of defense around and lay mines around ⑪

There are some caveats, so I'll briefly introduce them as well.

--The data to be POSTed, that is, the argument specified in data of ʻurllib.request.Request ()must be of typebytes. In short, str does not work, and you need to convert it using ʻencode () | etc. --Since the return value of http.client.HTTPResponse # read () that gets the response result is also of bytes type, use decode () etc. to convert it to str. -- json.dupms () will convert a Python object to a json string (str). There is also a method with a similar name, json.dump (), but this is different. --Similarly, json.loads () and json.load () are different. --ʻ The return value of urllib.request.urlopen () is http.client.HTTPResponse`.

Recommended Posts

POST json with Python3 script
[Python] Use JSON with Python
Post to slack with Python 3
Format json with Vim (with python)
Read json data with python
Python #JSON
[Python] POST wav files with requests [POST]
Quine Post with Qiita API (Python)
JSON encoding and decoding with python
Post multiple Twitter images with python
Easily post to twitter with Python 3
Write a batch script with Python3.5 ~
Script python file
FizzBuzz with Python3
Scraping with Python
Statistics with python
python script skeleton
Scraping with Python
Execute Python script with cron of TS-220
Python with Go
POST variously with Python and receive with Flask
Python script profiling
Twilio with Python
Convert Excel data to JSON with python
Integrate with Python
Post Test 3 (Working with PosgreSQL in Python)
Import python script
Play with 2016-Python
AES256 with python
Tested with Python
python starts with ()
Reading and writing JSON files with Python
with syntax (Python)
Bingo with python
Zundokokiyoshi with python
Excel with Python
Microcomputer with Python
Cast with python
Read JSON with Python and output as CSV
Post youtube soaring title to twitter with python3
[Improved version] Script to monitor CPU with Python
[Python3] Read and write with datetime isoformat with json
Run VMware vSphere 6 vSphere API with Python script (pyvmomi)
POST JSON in Python and receive it in PHP
Make JSON into CSV with Python from Splunk
Examine Python script bottlenecks with the cProfile module
Post an article with an image to WordPress with Python
Python script to get note information with REAPER
Serial communication with Python
Zip, unzip with python
Primality test with Python
Python with eclipse + PyDev.
Socket communication with Python
Data analysis with python 2
Scraping with Python (preparation)
Try scraping with Python.
Sequential search with Python
"Object-oriented" learning with python
Run Python with VBA
Solve AtCoder 167 with python
Serial communication with python