I am trying to send a request to Linkedin's rest share api. I have been receiving this error message:
{
"errorCode": 0,
"message": "Can not parse JSON share document.\nRequest body:\n\nError:\nnull",
"requestId": "ETX9XFEI7N",
"status": 400,
"timestamp": 1437910620120
}
The request is send through the following python code:
import requests,json
auth_token = "some auth token"
url = "https://api.linkedin.com/v1/people/~/shares?format=json&oauth2_access_token="+auth_token
headers = {'content-type': 'application/x-www-form-urlencoded','x-li-format':'json'}
data = {
"comment":"Check out developer.linkedin.com!",
"content":{
"title": "LinkedIn Developers Resources",
"description": "Leverage LinkedIn's APIs to maximize engagement",
"submitted-url": "https://developer.linkedin.com",
"submitted-image-url": "https://example.com/logo.png"
},
"visibility":{
"code": "anyone"
}
}
response = requests.post( url , json= data , headers=headers )
return HttpResponse( response )
I made sure that I followed all the instructions in their documentation and can't find the mistake I am making.
Note: i have tried json=data and data=data both are not working
Remove content-type from the headers dictionary.
requests sets the correct Content-Type when using the json keyword argument.
You have three basic problems:
Please read the documentation on oauth2; because you are not passing in the token correctly.
The share URL does not take a oauth2_token argument.
You have the wrong content-type header.
Related
I've been trying to connect my Spotify account using the requests module and I came across a problem
later on I tried to manipulate it on my Python code
import requests
URL = 'https://accounts.spotify.com/login/password'
payload = {
"username": "example#gmail.com",
"password": "123456",
"remember" : True
}
response = requests.post(URL , json=payload)
print(response.status_code)
OUTPUT : 415
what went wrong ?
I don't think this is how you should interact with Spotify from code.
It has an API and you should use tokens for authentication or anything else from password.
Anyway you can try setting the correct media type when making the request:
URL = 'https://accounts.spotify.com/login/password'
payload = {
"username": "example#gmail.com",
"password": "123456",
"remember" : True
}
headers = { 'Content-Type':'application/x-www-form-urlencoded' }
response = requests.post(URL , json=payload, headers=headers)
you cannot use this url to send post request as it has "recaptchaToken" which you need pass in your payload which is getting generated dynamically. Hence it is not a good idea to use this approach.
Instead you can use API to achieve the same.
https://github.com/plamere/spotipy
I am attempting to post some data through REST API in Python.
data.json
{
"LastModifiedAt": "2020-12-21T20:19:45.335Z",
...
...
}
I am using following code to POST the data.
with open('data.json') as fh:
data = json.load(fh)
headers = {
'Content-Type': 'application/json',
'X-API-Key':'ABC=='
}
response = requests.post('https://myurl.net/api/v1/resource/int_key/endpoint', headers=headers,data=data)
I always get following as response status_code = 400
{
"ModelState": {
"line": [
"Unexpected character encountered while parsing value: L. Path '', line 0, position 0."
]
},
"Message": "The request is invalid."
}
How do I debug this? My URL is correct according to API documentation. Why does it return "Bad Request" status code?
I replaced data with json and it worked.
response = requests.post('https://myurl.net/api/v1/resource/int_key/endpoint', headers=headers,json=data)
I used Postman as suggested by AndroidDev to debug this.
I'm sure this is a broader question that applies to more than just Reddit, but currently I am attempting to exchange a code for a user access token however I am not understanding how to implement the following steps:
https://github.com/reddit-archive/reddit/wiki/OAuth2#retrieving-the-access-token
If you didn't get an error and the state value checks out,
you may then make a POST request with code to the following URL to retrieve your access token:
https://www.reddit.com/api/v1/access_token
Include the following information in your POST data (NOT as part of the URL)
grant_type=authorization_code&code=CODE&redirect_uri=URI
Okay, so what I did was this:
headers = {
CLIENT_ID: CLIENT_SECRET,
}
r = requests.post(
url="https://www.reddit.com/api/v1/access_token",
data={
"grant_type": "authorization_code",
"code": code,
"redirect_uri": "http://127.0.0.1:5000/callback"
},
headers=headers
)
I think I am failing with the headers, I receive a 429 error, and I don't think I've understood how to arrange the headers correctly as it doesn't clearly explain in the above link.
The "user" is the client_id. The "password" for confidential clients is the client_secret. The "password" for non-confidential clients (installed apps) is an empty string.
CLIENT_ID and CLIENT_SECRET are obviously variables, and they are my Reddit App dev credentials.
EDIT:
I came up with this, it's gross but it seems to work
headers = {
"User-Agent": "MyApp v1.0",
"Authorization": "Basic " + str(base64.b64encode(str.encode(f"{CLIENT_ID}:{CLIENT_SECRET}")))[2:-1],
}
Is there a cleaner way to write that?
Final answer, using an inbuilt method in Python's request:
client_auth = requests.auth.HTTPBasicAuth(CLIENT_ID, CLIENT_SECRET)
r = requests.post(
url="https://www.example.com/api/v1/access_token",
auth=client_auth,
data={
"grant_type": "authorization_code",
"code": code,
"redirect_uri": "http://127.0.0.1:5000/callback"
},
headers={
"User-Agent": "MyApp v1.0",
}
)
I've been troubleshooting an issue when sending a PUT Request to the ETSY REST API,
when I make a PUT request, I get a signature invalid error. I have tried all the solutions found on google, but none seem to work.
Sending the same request through POSTMAN works, if I specify the auth parameters to go in the body. However when I try to replicate this using python's standard procedures I get the same invalid signature error.
Even if I export the python code for that exact request from postman, I get a signature invalid error when running said code in python.
This is the json data I need to send:
"products": [
{
"product_id":4262200422,
"sku":"00100012",
"property_values":[
{
"property_id":200,
"property_name":"Primary color",
"scale_id":null,
"scale_name":null,
"values":[
"Black"
],
"value_ids":[
1
]
}
],
"offerings":[
{
"offering_id":4128359213,
"price":{
"amount":200,
"divisor":100,
"currency_code":"GBP",
"currency_formatted_short":"\\u00a32.00",
"currency_formatted_long":"\\u00a32.00 GBP",
"currency_formatted_raw":"2.00"
},
"quantity":12,
"is_enabled":1,
"is_deleted":0
}
],
"is_deleted":0
},
{
"product_id":4031391357,
"sku":"00100013",
"property_values":[
{
"property_id":200,
"property_name":"Primary color",
"scale_id":null,
"scale_name":null,
"values":[
"Bronze"
],
"value_ids":[
1216
]
}
],
"offerings":[
{
"offering_id":4244423138,
"price":{
"amount":300,
"divisor":100,
"currency_code":"GBP",
"currency_formatted_short":"\\u00a33.00",
"currency_formatted_long":"\\u00a33.00 GBP",
"currency_formatted_raw":"3.00"
},
"quantity":56,
"is_enabled":1,
"is_deleted":0
}
],
"is_deleted":0
}
],
"price_on_property": [200],
"quantity_on_property": [200],
"sku_on_property": [200]
Etsy is using Oauth1, POST and GET requests work fine in Python, but don't work in POSTMAN, returning an invalid signature error.
Maybe they are doing something differently that causes this behaviour?
I need to build a request that simply takes product data, oauth1 details, and sends it to Etsy.
Please let me know what I'm missing.
I managed to get it working... turns out you aren't supposed to include the actual oauth parameters in the signature calculations.
This is the code I used to make a PUT request --- Class Definition.
class etsyClient:
def __init__(self, consumer_key, consumer_secret, resource_owner_key,
resource_owner_secret):
self.consumer_key = consumer_key
self.consumer_secret = consumer_secret
self.resource_owner_key = resource_owner_key
self.resource_owner_secret = resource_owner_secret
self.oauthclient = self.regen()
def regen(self, sig=oauth1.SIGNATURE_HMAC_SHA1):
client = oauth1.Client(self.consumer_key,
client_secret=self.consumer_secret,
resource_owner_key=self.resource_owner_key,
resource_owner_secret=self.resource_owner_secret,
signature_method=sig)
return client
Actual request code:
uri, headers, body = self.client.regen(sig=oauth1.SIGNATURE_PLAINTEXT).sign(
f"https://openapi.etsy.com/v2/listings/{self.product.listing.id}/inventory")
r = requests.session()
headers["Content-Type"] = "application/x-www-form-urlencoded"
data = {
"listing_id": self.product.listing.id,
"products": json.dumps(products),
'price_on_property': [200],
'quantity_on_property': [200],
'sku_on_property': [200]
}
a = r.put(uri, headers=headers, data=data)
I am trying to use Google's QPX Express API from python. I keep running into a pair of issues in sending the request. At first what I tried is this:
url = "https://www.googleapis.com/qpxExpress/v1/trips/search?key=MY_KEY_HERE"
values = {"request": {"passengers": {"kind": "qpxexpress#passengerCounts", "adultCount": 1}, "slice": [{"kind": "qpxexpress#sliceInput", "origin": "RDU", "destination": location, "date": dateGo}]}}
data = json.dumps(values)
req = urllib2.Request(url, data, {'Content-Type': 'application/json'})
f = urllib2.urlopen(req)
response = f.read()
f.close()
print(response)
based upon the code from: urllib2 and json
When I run the above code I get the following error message:
TypeError: POST data should be bytes or an iterable of bytes. It cannot be of type str.
I searched for a solution and adapted my code based upon the following question: TypeError: POST data should be bytes or an iterable of bytes. It cannot be str
I changed my code to this:
url = "https://www.googleapis.com/qpxExpress/v1/trips/search?key=AIzaSyCMp2ZnKI3J91sog7a7m7-Hzcn402FyUZo"
values = {"request": {"passengers": {"kind": "qpxexpress#passengerCounts", "adultCount": 1}, "slice": [{"kind": "qpxexpress#sliceInput", "origin": "RDU", "destination": location, "date": dateGo}]}}
data = json.dumps(values)
data = data.encode("utf-8")
req = urllib2.Request(url, data, {'Content-Type': 'application/json'})
f = urllib2.urlopen(req)
response = f.read()
f.close()
print(response)
However, when I run this code I get the following error message:
urllib.error.HTTPError: HTTP Error 400: Bad Request
I also tried changing utf-8 to ascii but I was unsuccessful. How can I get this working properly?
Here is a solution using the excelent requests library.
import json
import requests
api_key = "YOUR API KEY HERE"
url = "https://www.googleapis.com/qpxExpress/v1/trips/search?key=" + api_key
headers = {'content-type': 'application/json'}
params = {
"request": {
"slice": [
{
"origin": "TXL",
"destination": "LIM",
"date": "2015-01-19"
}
],
"passengers": {
"adultCount": 1
},
"solutions": 2,
"refundable": False
}
}
response = requests.post(url, data=json.dumps(params), headers=headers)
data = response.json()
print data
I am not sure why you request is not working. Maybe it is really the request parameters that were wrong. The date definitely needs to be in the future!
False needs to be in lowercase in JSON, so you need to quote it in Python, like this "refundable" : "false". Otherwise, your query looks good (obviously you'll need to update the date). By the way, it isn't good practice to include your API key in a public forum.