43

I have the following code that I'd like to update to Python 3.x The required libraries would change to http.client and json.

I can't seem to understand how to do it. Can you please help?

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

4 Answers 4

73
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>'
Sign up to request clarification or add additional context in comments.

8 Comments

@J.F.Sebastian I hesitated about it but did not bother to find out the details about it. Thank you for noticing.
Modify headers to "headers = {'Content-type': 'application/json', 'User-Agent': 'Python 3 Script'}" in order to get past the Github requirement developer.github.com/v3/#user-agent-required
How do I get the response.read() into a variable or write it into a file ? I get the error as "RemoteDisconnected: Remote end closed connection without response."
@Sarang open('myfile', 'wb').write(data) or open('myfile', 'w').write(data.decode('utf-8')
|
1

To make your code Python 3 compatible it is enough to change import statements and encode/decode data assuming utf-8 everywhere:

import json
from urllib.request import urlopen

data = {"text": "Hello world github/linguist№1 **cool**, and #1!"}
response = urlopen("https://api.github.com/markdown", json.dumps(data).encode())
print(response.read().decode())

See another https post example.

Comments

-1
conn = http.client.HTTPSConnection("st.auth.itc")
conn.request("POST", "/auth/realms/Staging/protocol/openid-connect/token", params, headers)
response = conn.getresponse()
print(response.status, response.reason)
data = response.read().decode()
return JsonResponse(json.loads(data))

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
-2
conn = http.client.HTTPSConnection('https://api.github.com/markdown')
conn.request("GET", "/markdown")
r1 = conn.getresponse()
print r1.read()

3 Comments

but where is the part where you are submitting the json encoded data to this url?
This is an incorrect response, it won't even succeed to initialize the HTTPSConnection().
note: the OP wants POST request, not GET. And as @joar noted the first arg of HTTPSConnection should be host, not URL.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.