I am required to change some data in a campaign using the apple search ads API which I haven't used before. I have managed to generate a token and do a get request for the data but when I make a put request the response received is an response[400].
The code im using is as follows:
import jwt
import json
import requests
headers={'Authorization': f'Bearer{"access token",
'X-AP-Context': f'orgId={orgId}',
}
payload = {"dailyBudgetAmount":{"amount": "300"}}
payload = json.dumps(payload, indent=1)
requests.put('https://api.searchads.apple.com/api/v4/campaigns/campaignId',json_data = payload, headers=headers)
Related
I have tried using a rest client (ARC)for doing a post request to a private API and I am getting correct response but when I switch to python and did the same request using the python request package , the response is this
b'{"code":"Invalid Checksum","message":"Invalid Checksum"}'
I am using the same URL , header and body tag. Where can I possibly go wrong .
Here is the code snippet
import requests
import json
request_args = {"Id": -1,"startDate": "2018-01-13","endDate": "2018-01-14","ProviderId": 1}
headers = {'Authorization':'xxxxxx','Content-Type':'application/json','content-md5':'yyyy'}
base_url = "https://myendpoint"
response = requests.post(base_url,data=request_args, headers=headers)
print(response.content)
I am trying to fetch some data from the udemy api. When I put a GET a request I get 403 status code
What I tried:
import requests
headers = {
'Authorization': 'Basic {BASE64_ENCODED(CLIENT_ID:CLIENT_SECRET)}',
}
response = requests.get('https://www.udemy.com/api-2.0/courses/', headers=headers)
I also tried using base64encode and using auth but that too didn't work.
According to Udemy,
To send authenticated requests, provide the client_id and client_secret values as a base64 encoded HTTP Authorization header.
curl --user {YOUR_CLIENT_ID}:{YOUR_CLIENT_SECRET} https://www.udemy.com/api-2.0/courses/
curl -H "Authorization: Basic {BASE64_ENCODED(CLIENT_ID:CLIENT_SECRET)}" https://www.udemy.com/api-2.0/courses/
Thanks in advance for your help guys!
well, that's because you're sending a string that says:
"Basic {BASE64_ENCODED(CLIENT_ID:CLIENT_SECRET)}"
you're not passing actual base64 encoded parameters.
for starters import base64 then use it to encode YOUR client_id and YOUR client_secret, you should be able to figure out how to obtain those fron Udemy's API documentation, ultimately it should look something like this:
import requests
import base64
client_id = <client_id you obtain from Udemy>
client_secret = <client_secret you obtain from Udemy>
client_id_secret = f"{client_id}:{client_secret}"
b64_client_id_secret = base64.encode(client_id_secret)
headers =
{
'Authorization': f'Basic {b64_client_id_secret}'
}
When making a call to the Genius API (the music lyric service) search capability to search for a specific song by title, my GET request is successfully processed and returns a HTTP status code of 200, but the JSON response returns no hits for the song I searched.
{u'meta': {u'status': 200}, u'response': {u'hits': []}}
Notice the value for the hits key is an empty array. This is strange, since when "testing" the same call on the Genius API Docs site https://docs.genius.com/#web_pages-h2 with the same OAuth2 access token I'm able to get 10 hits for the same search. I've tried searching multiple song titles with the same results.
I'm using Python 2.7.12, and I replaced my API call access token with AccessTOKEN below so I'm not sharing that publicly (though I was testing with the correct access token)
#!/usr/bin/env python
# -*- coding=utf-8 -*-
import requests
baseUrl = "http://api.genius.com"
headers = {'Authorization': 'Bearer AccessTOKEN'}
searchUrl = baseUrl + "/search"
songTitle = "Shelter"
data = {'q': songTitle}
response = requests.get(searchUrl, data=data, headers=headers)
json = response.json()
print json
Any ideas?
The data parameter is used for a POST request. Since this is a GET request, you should pass your data to the params parameter.
response = requests.get(searchUrl, params=data, headers=headers)
I'm trying to make a Python webapp write to Firebase DB using HTTP API (I'm using the new version of Firebase presented at Google I/O 2016).
My understanding so far is that the specific type of write I'd like to accomplish is made with a POST request to a URL of this type:
https://my-project-id.firebaseio.com/{path-to-resource}.json
What I'm missing is the auth part: if I got it correctly a JWT should be passed in the HTTP Authorization header as Authorization : Bearer {token}.
So I created a service account, downloaded its private key and used it to generate the JWT, added it to the request headers and the request successfully wrote to Firebase DB.
Now the JWT has expired and any similar request to the firebase DB are failing.
Of course I should generate a new token but the question is: I wasn't expecting to handle token generation and refresh myself, most HTTP APIs I'm used to require just a static api key to be passed in the request so my webapps could be kept relatively simple by just adding the stati api key string to the request.
If I have to take care of token generation and expiration the webapp logic needs to become more complex (because I'd have to store the token, check if it is still valid and generate a new one when not), or I could just generate a new token for every request (but does this really make sense?).
I'd like to know if there's a best practice to follow in this respect or if I'm missing something from the documentation regarding this topic.
Thanks,
Marco
ADDENDUM
This is the code I'm currently running:
import requests
import json
from oauth2client.service_account import ServiceAccountCredentials
_BASE_URL = 'https://my-app-id.firebaseio.com'
_SCOPES = [
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/firebase.database'
]
def _get_credentials():
credentials = ServiceAccountCredentials.from_json_keyfile_name('my_service_account_key.json', scopes=_SCOPES)
return credentials.get_access_token().access_token
def post_object():
url = _BASE_URL + '/path/to/write/to.json'
headers = {
'Authorization': 'Bearer '+ _get_credentials(),
'Content-Type': 'application/json'
}
payload = {
'title': title,
'message': alert
}
return requests.post(url,
data=json.dumps(payload),
headers=headers)
Currently for every request a new JWT is generated. It doesn't seem optimal to me. Is it possible to generate a token that doesn't expire?
Thanks for the code example. I got it working better by using the credentials.authorize function which creates an authenticated wrapper for http.
from oauth2client.service_account import ServiceAccountCredentials
from httplib2 import Http
import json
_BASE_URL = 'https://my-app-id.firebaseio.com'
_SCOPES = [
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/firebase.database'
]
# Get the credentials to make an authorized call to firebase
credentials = ServiceAccountCredentials.from_json_keyfile_name(
_KEY_FILE_PATH, scopes=_SCOPES)
# Wrap the http in the credentials. All subsequent calls are authenticated
http_auth = credentials.authorize(Http())
def post_object(path, objectToSave):
url = _BASE_URL + path
resp, content = http_auth.request(
uri=url,
method='POST',
headers={'Content-Type': 'application/json'},
body=json.dumps(objectToSave),
)
return content
objectToPost = {
'title': "title",
'message': "alert"
}
print post_object('/path/to/write/to.json', objectToPost)
Using Python, I'm trying to do a POST call to the Spotify API by following the instructions under the paragraph Client Credentials Flow at the link https://developer.spotify.com/web-api/authorization-guide/#client_credentials_flow and this is the code I have come up with.
However, I get Response [415] when I run it. Can anyone tell me what is wrong?
import pprint
import requests
import urllib2
import json
import base64
client_id='b040c4e03217489aa647c055265d0ac'
client_secret='2c2928bb7d3e43278424002d2e8bda46b'
authorization_param='Basic ' + base64.standard_b64encode(client_id + ':' + client_secret)
grant_type='client_credentials'
#Request based on Client Credentials Flow from https://developer.spotify.com/web-api/authorization-guide/
#Header must be a base 64 encoded string that contains the client ID and client secret key.
#The field must have the format: Authorization: Basic <base64 encoded client_id:client_secret>
header_params={'Authorization' : authorization_param}
#Request body parameter: grant_type Value: Required. Set it to client_credentials
body_params = {'grant_type' : grant_type}
url='https://accounts.spotify.com/api/token'
response=requests.post(url, header_params, body_params) # POST request takes both headers and body parameters
print response
The type of authentication that Spotify is requesting is just basic HTTP authentication. This is a standardised form of authentication which you can read more about here. The requests library supports basic authentication without requiring you to create the headers yourself. See the python requests documentation for information.
The code below uses the request library authentication to connect to the Spotify API.
import requests
client_id = # Enter your client id here
client_secret = # Enter your client secret here
grant_type = 'client_credentials'
#Request based on Client Credentials Flow from https://developer.spotify.com/web-api/authorization-guide/
#Request body parameter: grant_type Value: Required. Set it to client_credentials
body_params = {'grant_type' : grant_type}
url='https://accounts.spotify.com/api/token'
response=requests.post(url, data=body_params, auth = (client_id, client_secret))
print response
I created a test account with Spotify and created a test client id and client secret which worked find for this. I got a response 200 back using python 2.7.6 and requests 2.2.1.