8

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

Actually i am trying to do this; use google shortener api. Maybe i misunderstood :/

Thanks you in advance :)

iskorum
  • 1,137
  • 1
  • 16
  • 27

3 Answers3

14

The answer working great. 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 requests package; code and doc

Community
  • 1
  • 1
iskorum
  • 1,137
  • 1
  • 16
  • 27
5

To send an POST request with 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)
iskorum
  • 1,137
  • 1
  • 16
  • 27
Victor Castillo Torres
  • 10,581
  • 7
  • 40
  • 50
0
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']
Pang
  • 9,564
  • 146
  • 81
  • 122