Nastya
Nastya

Reputation: 31

Get and Put requests for json data format using urllib(2)

I need to implement "put" and "get" REST API requests for sending a JSON file. The problem is that it has to be done using urllib or urllib2 module (e.g. no requests module).

Is there any brief tutorial on how to do it?

Thanks!

Upvotes: 2

Views: 1955

Answers (1)

rts
rts

Reputation: 379

I assume that you're using python3. Here's how you can make simple put request with the standard library:

from urllib.request import Request, urlopen
import json

url, data = 'https://example.com', {'key': 'value'}
data_bytes = bytes(json.dumps(data), encoding='utf8')
request = Request(url, method='PUT', data=data_bytes, headers={'Content-Type': 'application/json'})

with urlopen(request) as response:
  print(response.read())

Upvotes: 3

Related Questions