Python http.client json request and response. How?

import http.client
import json

connection = http.client.HTTPSConnection('api.github.com')

headers = {'Content-type': 'application/json'}

foo = {'text': 'Hello world github/linguist#1 **cool**, and #1!'}
json_foo = json.dumps(foo)

connection.request('POST', '/markdown', json_foo, headers)

response = connection.getresponse()
print(response.read().decode())

I will walk you through it. First you’ll need to create a TCP connection that you will use to communicate with the remote server.

>>> connection = http.client.HTTPSConnection('api.github.com')

http.client.HTTPSConnection()

Thẹ̣n you will need to specify the request headers.

>>> headers = {'Content-type': 'application/json'}

In this case we’re saying that the request body is of the type application/json.

Next we will generate the json data from a python dict()

>>> foo = {'text': 'Hello world github/linguist#1 **cool**, and #1!'}
>>> json_foo = json.dumps(foo)

Then we send an HTTP request to over the HTTPS connection.

>>> connection.request('POST', '/markdown', json_foo, headers)

Get the response and read it.

>>> response = connection.getresponse()
>>> response.read()
b'<p>Hello world github/linguist#1 <strong>cool</strong>, and #1!</p>'

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)