Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (16.4k points)

I have the accompanying code that I'd prefer to update it to Python 3.x The necessary libraries would change to http.client and json. 

I can't see how to do it. Would you be able to kindly assist?

import urllib2

import json

data = {"text": "Hello world github/linguist#1 **cool**, and #1!"}

json_data = json.dumps(data)

req = urllib2.Request("https://api.github.com/markdown")

result = urllib2.urlopen(req, json_data)

print '\n'.join(result.readlines())

1 Answer

0 votes
by (26.4k points)

Look at the below code:

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 give a walk you through it. In the first place, you'll need to make a TCP connection that you will use to speak with the remote server. 

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

-- http.client.HTTPSConnection()

Thẹ̣n you should determine the request headers. 

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

For this situation, we're saying that the solicitation body is of the sort application/json. 

Then, we will produce the JSON information from a python dict()

>>> foo = {'text': 'Hello world github/linguist#1 **cool**, and #1!'}

>>> json_foo = json.dumps(foo)

Then, we will send a HTTP request over HTTP's connection

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

Now get response & read it.

>>> response = connection.getresponse()

>>> response.read()

b'<p>Hello world github/linguist#1 <strong>cool</strong>, and #1!</p>'

Wanna become a Python expert? Come and join the python certification course and get certified.

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...