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)
Related
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)
I wrote a python script which sends POST requests to some particular website. In order to perform this request, I need the authorization token which keeps changing. my current solution is to use Chrome Dev tools (Network tab) to obtain the new token. I was wondering if there is any way to obtain the new token automatically, or any other way to get around this problem.
this is my current code:(Note that in the provided code general text has been replaced with "...")
import requests
import json
url = "..."
payload = {...}
headers = {...,
"Authorization": "Bearer ...",
...}
response = requests.post(url, data=json.dumps(payload), headers=headers)
I'm trying to use this service, Buffer, to publish a post on Facebook through API.
Here's my code:
params = {
'profile_ids': ids,
'text': "text",
'access_token': access_token
}
r = requests.post('https://api.bufferapp.com/1/updates/create.json', params=params)
print r.json()
print(r.url)
But when run I it, it prints out this message:
{"success":false,"message":"Please select at least one account to post from.","code":1004}
This is the URL used to make the request:
https://api.bufferapp.com/1/updates/create.json?access_token=ACCESS_TOKEN&text=TEXT&profile_ids=LIST_WITH_PROFILE_IDS
I made sure the id is correct and I got it both manually and through API still, I get the same message.
The only required parameter is the profile_ids which should be an array. Here's the documentation on their website about publishing posts("updates"): https://buffer.com/developers/api/updates
What am I doing wrong here?
It seems that the API expects the data in the post request payload, not as url parameters.
Use data, not params.
r = requests.post('https://api.bufferapp.com/1/updates/create.json', data=params)
# -------------------------------------------------------------------^^^^ here
Using Python requests, I am trying to log in a portal url which forwards to another url. I have read several posting on this subject and even tried:
1) create a session with request get and retrieve csrf token
2) use the csrf token from previous step and do a post on portal URL with payload being the username/password / and csrf token (the same info passed when I use developer tools .
3) after step 2 I still get p.text below as enter username and password and does not show the page behind login and indicates it is looking for me to login
s = requests.Session()
g = s.get("myPortalURL")
resp = g.text
for item in resp.split("\n"):
if "csrf_token" in item:
print (item)
csrfToken = item.strip().split("value=")[1].replace("\"", "").replace("/>","")
data = {'Username': self.pythonDataDict["portalUsername"], 'Password': self.pythonDataDict["portalPassword"],
'csrf_token': csrfToken}
print ("payload= ", data)
headers = {'content-type': 'application/x-www-form-urlencoded'}
p = s.post("myPortalURL", headers=headers, data=data)
soup = BeautifulSoup(p.text)
print (p.text)
Here are some possible issues with your code:
From personal experience; the URL to the login page should be different to the URL for the main page.
There is information missing in data, ALL of the required data needs to be entered in the form,
You may need to include additional request headers
Your code to get the csrf_token could be prone to returning incorrect data depending on the nature of that token (although all tokens vary so it may not)
Also as a side note, it is generally more idiomatic to use a with statement when using a session, e.g.
with requests.Session() as s:
initial_response = s.get("login_url")
# def createForm()...
main_response = s.get("target_url", data = data, headers = headers)
# rest of code...
It would also be extremely helpful if you could include the URL of the page you are trying to access if that is possible.
I am trying to play with the Hacker News API found here, especially the live data section.
I am currently trying to print the response I get for every new item that I get from the /v0/maxitem API.
Given below is the code that I currently have:
import pyrebase
from config import config
import requests
firebase = pyrebase.initialize_app(config)
firebase_db = firebase.database()
_BASEURL_ = "https://hacker-news.firebaseio.com/v0/item/"
def print_response(id):
headers = {"Content-Type": "application/json"}
print(_BASEURL_ + str(id) + ".json")
response = requests.get(_BASEURL_ + str(id) + ".json", headers=headers)
print(response.content)
def new_post_handler(message):
print(message["data"])
print_response(message["data"])
my_stream = firebase_db.child("/v0/maxitem").stream(new_post_handler,
stream_id="new_posts")
I am able to get a valid response the first time requests.get runs. But the second time, I always get a NULL value for the content of the response.
The GET URL works on postman though, able to get a valid response there. The issue seems to particularly be with how the requests module is treating the URL the second time.
Any help greatly appreciated.