Django creates / makes a POST request with headers

I want to make a POST request programmatically with custom headers. How can i do this?

I'm actually trying to do this ; use google shortener api. Perhaps I misunderstood: /

Thank you in advance :)

+4
source share
3 answers

To send a POST request using Python and with headers, you can do something like

import urllib2 import json data = {'data':'data'} url = api_url opener = urllib2.build_opener(urllib2.HTTPHandler) request = urllib2.Request(url, data=json.dumps(data)) request.add_header("Content-Type", "application/json") #Header, Value opener.open(request) 
+5
source

answer works fine. But found another solution ;

 import requests import json url = 'https://www.googleapis.com/urlshortener/v1/url' data = {'longUrl': 'http://www.google.com/'} headers = {'Content-Type': 'application/json'} r = requests.post(url, data=json.dumps(data), headers=headers) 

then

 answer = json.loads(r.text) 

or

 answer = r.json() 

Here is the requests package; code and doc

+10
source
 import json import requests def short_url(url): post_url = 'https://www.googleapis.com/urlshortener/v1/url?key={API_KEY}' params = json.dumps({'longUrl': url}) response = requests.post(post_url,params,headers={'Content-Type': 'application/json'}) return response.json()['id'] 
0
source

Source: https://habr.com/ru/post/1487216/


All Articles