how to use Google Shortener API with Python - python

I want to write an app to shorten url. This is my code:
import urllib, urllib2
import json
def goo_shorten_url(url):
post_url = 'https://www.googleapis.com/urlshortener/v1/url'
postdata = urllib.urlencode({'longUrl':url})
headers = {'Content-Type':'application/json'}
req = urllib2.Request(
post_url,
postdata,
headers
)
ret = urllib2.urlopen(req).read()
return json.loads(ret)['id']
when I run the code to get a tiny url, it throws an exception: urllib2.HTTPError: HTTP Error 400: Bad Requests.
What is wrong with this code?

I tried your code and couldn't make it work either, so I wrote it with requests:
import requests
import json
def goo_shorten_url(url):
post_url = 'https://www.googleapis.com/urlshortener/v1/url'
payload = {'longUrl': url}
headers = {'content-type': 'application/json'}
r = requests.post(post_url, data=json.dumps(payload), headers=headers)
print(r.text)
Edit: code working with urllib:
def goo_shorten_url(url):
post_url = 'https://www.googleapis.com/urlshortener/v1/url'
postdata = {'longUrl':url}
headers = {'Content-Type':'application/json'}
req = urllib2.Request(
post_url,
json.dumps(postdata),
headers
)
ret = urllib2.urlopen(req).read()
print(ret)
return json.loads(ret)['id']

I know this question is old but it is high on Google.
Another thing to try is the pyshorteners library it is very simple to implement.
Here is a link:
https://pypi.python.org/pypi/pyshorteners

With an api key:
import requests
import json
def shorten_url(url):
post_url = 'https://www.googleapis.com/urlshortener/v1/url?key={}'.format(API_KEY)
payload = {'longUrl': url}
headers = {'content-type': 'application/json'}
r = requests.post(post_url, data=json.dumps(payload), headers=headers)
return r.json()

Related

how to make a release using the github api

I tried to do it by examples, but at startup it outputs a 404 error
import requests
payload ={"tag_name":"v1.0.0","target_commitish":"master","name":"v1.0.0","body":"Description of the release","draft":"false","prerelease":"false","generate_release_notes":"false"}
url = 'https://api.github.com/repos/user/test/releases'
headers = {'Authorization': 'token token'}
response = requests.post(url, headers=headers,data=payload)
print(response)
Try:
import requests
payload ={"tag_name":"v1.0.0","target_commitish":"master","name":"v1.0.0","body":"Description of the release","draft":"false","prerelease":"false","generate_release_notes":"false"}
url = 'https://api.github.com/repos/user/test/releases'
headers = {'Authorization': 'token token', 'Accept': 'application/vnd.github+json'}
response = requests.post(url, headers=headers, json=payload)
print(response)

How to create a simple REST api WEB application with Python

We can make REST api application with spring boot by start.spring.io web site easily, anyone know any good website through which I can get the skeleton REST api project with python? My intention is to make REST api application with python.
One of the ways to do this is by using the requests module in Python. Import it into your code with the following command:
import requests
Now, each API is different, so you'll have to see with the vendor what the requirements are. For testing and learning purposes, I recommend using httpbin (https://httpbin.org). You can test pretty much anything there.
Here are a few simple requests:
#returning status
url = 'https://httpbin.org/post'
response = requests.post(url)
print(response.status_code)
print(response.ok)
#sending data/getting text response
url = 'https://httpbin.org/post'
params = {'Jello':'World'}
response = requests.post(url, params=params)
print(response.text)
#sending data/getting json response
url = 'https://httpbin.org/post'
params = {'Jello':'World'}
response = requests.post(url, params=params)
print(response.json())
#sending time data to server
import datetime
url = 'https://httpbin.org/post'
params = {'Time':f'{datetime.datetime.now()}'}
response = requests.post(url, params=params)
print(response.text)
#Params vs Data
#params
url = 'https://httpbin.org/post'
params = {'username':'jsmith','password':'abc123'}
response = requests.post(url, params=params)
print(response.text)
#data
url = 'https://httpbin.org/post'
payload = {'username':'jsmith','password':'abc123'}
response = requests.post(url, data=payload)
print(response.text)
# ********* HEADERS **********
url = 'https://httpbin.org/get'
response = requests.get(url)
print(response.text)
url = 'https://httpbin.org/post'
headers = {'content-type': 'multipart/form-data'}
response = requests.post(url,headers=headers)
print(response.request.headers) #client request headers
print(response.headers) #server response headers
print(response.headers['content-type']) #request header value from server
To use actual APIs, I suggest RapidAPI (https://rapidapi.com/), which is a hub where you can connect to thousands of APIs. HEre is a sample code using Google translate:
#RapidAPI
#Google Translate
import requests
url = "https://google-translate1.p.rapidapi.com/language/translate/v2"
text = 'Ciao mondo!'
to_lang = 'en'
from_lang = 'it'
payload = f"q={text}&target={to_lang}&source={from_lang}"
headers = {
'content-type': "application/x-www-form-urlencoded",
'accept-encoding': "application/gzip",
'x-rapidapi-host': "google-translate1.p.rapidapi.com",
'x-rapidapi-key': "your-API-key"
}
response = requests.post(url, data=payload, headers=headers)
print(response.json()['data']['translations'][0]['translatedText'])

Pull data from cm commerce using x-api-key

i am trying to pull data by referencing this guide.
I'm a little new. can i just pull data with api key and url. Because i have only api key and url. I don't have any of the other parameters. Here are the ways i tried:
import urllib.parse
import urllib.request
url = "https://commerce.campaignmonitor.com/api/v1/abandoned-carts/campaigns"
header={"x-api-key" : 'my_api_key'}
post_param = urllib.parse.urlencode({
'user' : 'i_dont_know',
'status-update' : 'i_dont_know'
}).encode('UTF-8')
req = urllib.request.Request(url, post_param, header)
response = urllib.request.urlopen(req)
and this:
from requests.auth import HTTPBasicAuth
import requests
import urllib
url ="https://commerce.campaignmonitor.com/api/v1/abandoned-carts/campaigns"
headers = {"Accept": "application/json"}
auth = HTTPBasicAuth('my_api_key', 'i_dont_know')
req = requests.get(url, headers=headers , auth=auth)
response = urllib.request.urlopen(req)
but i have error:
AttributeError: 'Response' object has no attribute 'type'
in other methods, I get 401 error
python-requests alone can do this for you (no need for urllib).
You have the API key so you shouldn't use the HTTPBasicAuth
this should work for you:
import requests
url ="https://commerce.campaignmonitor.com/api/v1/abandoned-carts/campaigns"
# like the doc says, provide API key in header
headers = {"Accept": "application/json",
'X-ApiKey': 'my_api_key'}
req = requests.get(url, headers=headers)
print(req.json())

How to get the request from api having account key

import requests
import json
def test_request_response():
# Send a request to the API server and store the response.
data = { 'username' : 'sxxxt#xxx.com', 'password' : 'xxxxe' }
headers = {'Content-type': 'application/json'}
response = requests.get('https://xx.xxx.com/xx/xx',headers=headers,data=json.dumps(data))
return response
test_request_response()
output
I have an api key also API_KEY = '0x-x-x-x0 is there any I can give API_KEY in requests.get as like username and password
example in headers headers = {'Content-type': 'application/json','X-IG-API-KEY':'0x-x-x-x0'}
is this what you are looking for ?
from requests.auth import HTTPBasicAuth
import requests
url = "https://api_url"
headers = {"Accept": "application/json"}
auth = HTTPBasicAuth('apikey', '1234abcd')
files = {'filename': open('filename','rb')}
req = requests.get(url, headers=headers , auth=auth , files=files)
reference : Calling REST API with an API key using the requests package in Python

how to pass a response object to requests in python?

import json
import requests
url = 'smeurl/execute'
payload ={"sme":"yes"}
headers = {'Accept': 'application/json','content-type': 'application/json'}
r = requests.post(url, data=json.dumps(payload), headers=headers)
responseObj =r.json()
print responseObj
url="myurl/get?key="+str(responseObj )+""
r = requests.get(url, headers=headers)
if r.status_code == 200:
print r.json()
I want to pass responseObj to requests.get() in python but when its run its showing as
ValueError: No JSON object could be decoded
inspite of
responseObj prints what is expected(ie key)
also this url when run in RESTClient with this key
its giving json datawhich is what to be brought to python code.
Any suggestions pls?

Categories

Resources