Having trouble converting cURL POST command to python requests - python-3.x

I am trying to convert a block of cURL to python requests. I get the following error when I do:
{'error': 'invalid_request', 'error_description': 'request is missing a required parameter or malformed.'}
What am I translating incorrectly?
curl
POST /identity/v1/oauth2/token HTTP/1.1
Host: api.sandbox.ebay.com
Authorization: Basic <B64-encoded-oauth-credentials>
Content-Type: application/x-www-form-urlencoded
grant_type=authorization_code&code=<URL-decoded-auth-code>&redirect_uri=<your_redirect_uri>
my_call.py
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
a 'Authorization': f'Basic {<Base64 encoded value>}'
}
data = {
'grant_type': 'authorization_code',
'code': client_id # str,
'redirect_uri': url # str,
'scope': 'https://api.ebay.com/oauth/api_scope/sell.inventory.readonly',
}
def get_oath_token():
url = 'https://api.ebay.com/identity/v1/oauth2/token'
r = requests.post(url, headers=headers, data=data)
print(r.json())

Related

Polar accesslink API POST users not working

I'm currently trying to implement Polar accesslink API on an app, but when trying to POST a new user I still get this error:
url: 'https://www.polaraccesslink.com/v3/users/',
status: 400,
statusText: 'Bad Request',
headers: Headers { [Symbol(map)]: [Object: null prototype] },
counter: 0
I already have the authorization token, which I know expires every 10min, and I'm using the service through a function that takes the token and the userID as parameters. This is my code:
postUser(memberId: string, token: string) {
const inputBody = { 'member-id': memberId };
const headers = {
'Content-Type': 'application/xml', 'Accept': 'application/json', 'Authorization': 'Bearer ' + token
};
const options = {
method: "POST",
headers: headers,
body: JSON.stringify(inputBody)
}
return new Promise<object>((resolve, reject) => {
fetch('https://www.polaraccesslink.com/v3/users', options)
.then(function(res: any) {
console.log(res)
return res.json();
}).then(function(body: any) {
console.log(body);
});
})
}
I'm implementing it the same way as it is specified in https://www.polar.com/accesslink-api/?javascript--nodejs#users but really don't know what might I be doing wrong. Thanks for helping me!.
I don't have experience with this specific API but i can see you send in the header Content-Type the value application/xml but the request body is JSON formatted.
Try send application/json in that header.
The Content-Type header is used in HTTP to specify the body mime type.
more info in: Content-Type HTTP Header - MDN
I also see this is the exact code in the sample but notice they have 2 sample requests and 2 sample results, one in XML and one in JSON each.
Any ideea why this POST gives 'invalid_Request'?
curl --location --request POST 'https://polarremote.com/v2/oauth2/token?grant_type=authorization_code&code=1f9edc0c5e60a0bab4fd3f1f00571a58' --header 'Authorization: Basic ... DA4OS05ZDc2LTJlNTQwZjFkZTc5ZA==' --header 'Content-Type: application/x-www-form-urlencoded' --header 'Accept: application/json'

axios equivalent of http requests?

I want to make the following http request
POST /v1/images HTTP/1.1
Host: api.medium.com
Authorization: Bearer 181d415f34379af07b2c11d144dfbe35d
Content-Type: multipart/form-data; boundary=FormBoundaryXYZ
Accept: application/json
Accept-Charset: utf-8
--FormBoundaryXYZ
Content-Disposition: form-data; name="image"; filename="filename.png"
Content-Type: image/png
IMAGE_DATA
--FormBoundaryXYZ--
It is Medium API
I have attempted following.
var axios = require("axios")
var data = (await axios("https://example.com/image.png")).data;
axios.post("https://api.medium.com/v1/images",{image: data},{
headers: {
"Content-Type" : "multipart/form-data",
"Authorization" : "Bearer " + process.env.key
}
}).then(x=>console.log(x.data))
And I get following error.
Error: Request failed with status code 400
It uses Medium API to upload image, I want to fetch a remote image, and convert it into multipart/form-data and upload it via API, the HTTP request seems confusing, I want the equivalent axios code, someone please help?
Try using FormData instead of plain object?
Example should be like this
const formData = new FormData();
formData.append('image', data);
axios.post('https://api.medium.com/v1/images', formData, {
headers: {
"Content-Type" : "multipart/form-data",
"Authorization" : "Bearer " + process.env.key
}
});
Reference: How to post a file from a form with Axios

Unable to post request successfully when I select raw json on Postman

I'm getting a bad request from postman when I make a request using raw json on Postman. The POST request accepts the following payload:
{"BusinessID": 34222222}
When I select form-data the request is successful.
I also copied the Python code from postman and executed it but I get a bad request.
Screenshot
The same applies when I try to run the code below.
query=99858585
url = "https://xxxxxxxxxxxxx.co.io/permit/api/checkBusiness"
payload = "{\"BusinessID\": query}"
headers = {
'Content-Type': "application/json",
'User-Agent': "PostmanRuntime/7.20.1",
'Accept': "*/*",
'Cache-Control': "no-cache",
'Postman-Token': "1bda2a65-6ed4-45d2-8029-5e70efa336ec,c1a967af-856e-4ab0-ad88-83b0b5c496df",
'Host': "xxxxxxxxxxxxxxxxx.co.io",
'Accept-Encoding': "gzip, deflate",
'Content-Length': "23",
'Cookie': "ci_session=hnv0nsiksienscujctqmdm5mp2b0dp4q",
'Connection': "keep-alive",
'cache-control': "no-cache"
}
response = requests.request("POST", url, data=payload, headers=headers)
print(response.json())
When I select form-data the request is successful
Headers after selecting form-data*

from docusign sdk i am trying to get envelope but getting "Reason: The URL provided does not resolve to a resource." 404 error

I am trying to create envelope from SDK but getting error like this
Reason: The URL provided does not resolve to a resource.
HTTP response headers: HTTPHeaderDict({'Cache-Control': 'no-cache', 'X-DocuSign-TraceToken': '22dad523-9f77-4b83-9481-1e376faf60d8', 'Date': 'Thu, 05 Dec 2019 13:02:26 GMT', 'Content-Length': '0'})
def worker(args):
"""
1. Create the envelope request object
2. Send the envelope
"""
envelope_args = args["envelope_args"]
#print(args)
#print("envelope arrrgggsss")
#print(envelope_args)
# 1. Create the envelope request object
envelope_definition = make_envelope(envelope_args)
#print(envelope_definition)
# 2. call Envelopes::create API method
# Exceptions will be caught by the calling function
api_client = ApiClient()
api_client.host = args["base_path"]
print(api_client.host)
api_client.set_default_header("Authorization", "token" + args["ds_access_token"])
envelopes_api = EnvelopesApi(api_client)
results = envelopes_api.create_envelope(args['account_id'], envelope_definition=envelope_definition)
#print(results)
envelope_id = results.envelope_id
app.logger.info(f"Envelope was created. EnvelopeId {envelope_id}")
return {"envelope_id": envelope_id}
Before that i try to get the token from the following code
def oauth2_token_request(root_url, username, password,
integrator_key):
url = root_url + '/oauth2/token'
data = {
'grant_type': 'password',
'client_id': integrator_key,
'username': username,
'password': password,
'scope': 'api',
}
headers = {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
}
response = requests.post(url, headers=headers, data=data)
print(response)
if response.status_code != 200:
raise exceptions.DocuSignOAuth2Exception(response.json())
return response.json()['access_token']
def oauth2_token_revoke(root_url, token):
url = root_url + '/oauth2/revoke'
data = {
'token': token,
}
headers = {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
}
response = requests.post(url, headers=headers, data=data)
return response
# if response.status_code != 200:
# raise exceptions.DocuSignOAuth2Exception(response.json())
It seems you are hitting wrong API endpoint as
/restapi/v2.1/accounts/9286679/restapi/v2.1/accounts/9286679/envelopes
whereas the correct URI is
/restapi/v2.1/accounts/9286679/envelopes
check your "base_path" value.

Unable to get Python requests with API token

This is my code:
import requests
API key correct
api_key = c87cabcf1b479b807a7b3ba8xxxxxxxxxxxxxx
headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Token token=api_key'
}
Getting a List of serves from this API
r = requests.get('https://myserver/api/v1.1/server/', headers = headers, verify=False)
print(r.json())
print (r.status_code)
I am getting the error below. I checked my token correct one and not expires.
r.json() : {'error': {'code': 'error', 'description': 'Authentication credentials were not provided.'}}
r.status_code : 401
I missed somewhere in the header.
I guess problem is may be in your third line of header. Try it like this.
'Authorization': 'Token ' + api_key

Resources