Response 401 with python requests - python-requests

import requests
token = {
"access_token": "q3eFsG5ONt6fvdJsB3AAXL38KBAwrdCJ0",
"api_server": "https:\/\/api07.iq.questrade.com\/",
"expires_in": 1800,
"refresh_token": "Y3p43laee75kfDxzDWrONoNpkhgAFUyb0",
"token_type": "Bearer"
}
uri = "https://api01.iq.questrade.com/v1/markets"
headers = {'Authorization': 'Bearer {}'.format(token.get('access_token'))}
rt = requests.get(uri, headers=headers)
response = rt.json()
I do not understand what is happening here because token is updated, but I got <Response [401]>. What do I need to do to fix the problem?

Your mistake is here:
"api_server": "https:\/\/api07.iq.questrade.com\/"
You have \/, you should use the usual one:
"api_server": "https://api07.iq.questrade.com/"

Related

Ionic 3 - Http Get 401 (Unauthorized)

I’m calling a service using a token
Failed to load resource: the server responded with a status of 401 (Unauthorized)
Http failure response for http://localhost:65291/api/post: 401 Unauthorized
The same call works in Postman with Headers;
Content-Type: application/json
Authorization: Bearer token
The function in ionic is
getPosts() {
var header = new HttpHeaders({ "Content-Type": "application/json" });
header.append("Authorization", "Bearer " + this.token);
console.log("Bearer " + this.token);
return new Promise(resolve => {
console.log(this.apiUrl + '/post');
this.http.get(this.apiUrl + '/post', { headers: header}).subscribe((data: Post[]) => {
resolve(data);
}, err => {
console.log(err);
});
});
}
Added a log for the token to be sure that is adding it to the header correctly (the token is fine).
The apiUrl variable has value http://localhost:65291/api.
What is wrong here? Cors is enabled… Postman works ok…
Thanks
I think you definitely have client side problem (since its 401 and also you mention Postman works ok).
I had similar issues when I tried to append headers in the same fashion you did so I would suggest trying this (to eliminate this problem):
getPosts() {
// try forming headers object in one go:
let token = "Bearer "+this.token
let headers = new HttpHeaders({
"Content-Type": "application/json",
"Authorization": token
});
// now here I am not sure why you do promise wrapping this way, but then I would suggest:
return this.http.get(this.apiUrl + '/post', { headers: headers })
.toPromise()
.then((data: Post[]) => { // Success
console.log(data);
resolve(data);
}, (err) => {
console.log(err);
});
}
If the problem is still there - please share which version of Angular and Http module you are using?
Also check out this issue here: How to correctly set Http Request Header in Angular 2
And specifically this answer if you are on Angular 4.3+:
How to correctly set Http Request Header in Angular 2
After a while I found the problem,
header.append("Authorization", "Bearer " + this.token); is wrong. It worked using
let headers = new HttpHeaders({"Authorization: " + "Bearer " + this.token})
Setting multiple headers:
this.http
.post('api/items/add', body, {
headers: new HttpHeaders({
'Authorization': 'my-auth-token',
'x-header': 'x-value'
})
}).subscribe()
I had a similar problem, it works on postman and cors enabled but in the app doesn't work, my problem was i have / at the end of the URL in the API security config, and i was making the request without /, i just remove it from request URL,
also you can add /* in security config or put / in your app, the URL must be the same.
(maybe you have solved your issue and it was different issue but this is a possibe solution)

LinkedIn returns 401 REST API when making request with HttpClient

I am unable to retrieve the profile details when making a call the /people endpoint.
using(HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token.TempToken);
client.DefaultRequestHeaders.Add("x-li-format", "json");
var response = await client.GetAsync("https://api.linkedin.com/v1/people/~?format=json");
if (response.IsSuccessStatusCode)
{
return "success";
}
return "failed";
}
I can confirm that the token is coming through at this point. And I have just successfully authorized before I pass the token to this code block.
Below is my request message:
{Method: GET, RequestUri: 'https://api.linkedin.com/v1/people/~?format=json', Version: 1.1, Content: , Headers:
{
Authorization: Bearer AQTgH0PIdKoSnCbbDaFhubm2q3wJcmv-qvxOqcd42qbdzfDja4DUj5Cs0YMk6RZ37Gv_0WWsrv24C9vhOG7d8M3IlPS9fez9DjwNu37U71PLiTzGPN-I4j1FsY7aJeMmf9I1v_XXXXXXXXXXXXXXXXX_3ADwlS6_a9
x-li-format: json
x-ms-request-root-id: 388de07b-44400de197c25bd0
x-ms-request-id: |388de07b-44400de197c25bd0.1.
Request-Id: |388de07b-44400de197c25bd0.1.
}}
Any assistance would be greatly appreciated.
Thanks
I was having the same issue for a few hours on 21-June. Fortunately it resolved itself so I'm assuming a linkedin api problem.

How to send Get and Post request with POCO Library and OAuth2

I have a native window app program,and want access API of gitlab service,hope to get token using name and password with using POCO Library and OAuth2,but I don't know how to send Get and Post request to gitlab with OAuth2,and using POCO Library, please give me a example.
Here is the data that needs to be sent and received.
Requesting access token
POST request to /oauth/token with parameters:
{
"grant_type" : "password",
"username" : "user#example.com",
"password" : "secret"
}
Then, you'll receive the access token back in the response:
{
"access_token": "1f0af717251950dbd4d73154fdf0a474a5c5119adad999683f5b450c460726aa",
"token_type": "bearer",
"expires_in": 7200
}
First you need to create a HTTPRequest object like so:
Poco::Net::HTTPClientSession* session = Poco::Net::HTTPSessionFactory::defaultFactory().createClientSession(serverUri);
Poco::Net::HTTPRequest request(Poco::Net::HTTPRequest::HTTP_POST, serverUri.getPathAndQuery(), Poco::Net::HTTPMessage::HTTP_1_1);
Then create a HTMLForm:
Poco::Net::HTMLForm form;
form.add("grant_type", "password");
form.add("client_id", "client token");
form.add("client_secret", "client secret");
form.add("username", "user#example.com");
form.add("password", "secret");
form.prepareSubmit(request);
Send the request and write the form data into the output stream of the request:
std::ostream& requestStream = session->sendRequest(request);
form.write(requestStream);
Get the response out of the session:
Poco::Net::HTTPResponse response;
std::istream& responseStream = session->receiveResponse(response);
std::stringstream rawJson;
Poco::StreamCopier::copyStream(responseStream, rawJson);
Parse the raw JSON:
Poco::JSON::Parser parser;
Poco::JSON::Object::Ptr authObj = parser.parse(rawJson).extract<Poco::JSON::Object::Ptr>();
Create a new session for next request and attach an authorization header to the request:
Poco::Net::HTTPClientSession* dataSession = Poco::Net::HTTPSessionFactory::defaultFactory().createClientSession(dataUri);
Poco::Net::HTTPRequest dataRequest(Poco::Net::HTTPRequest::HTTP_GET, dataUri.getPathAndQuery(), Poco::Net::HTTPMessage::HTTP_1_1);
dataRequest.add("Authorization", "Bearer " + authObj->get("access_token"));
dataSession->sendRequest(dataRequest);
Get the response and read the data from stream:
std::stringstream data;
Poco::Net::HTTPResponse dataResponse;
Poco::StreamCopier::copyStream(dataSession->receiveResponse(dataResponse), data);
Hope it helps or points into the right direction.

Python : POST a Multipart-Encoded File

Trying to upload a file using requests module, but encountered Internal Server Error Its the same using poster module too:
import requests
url = "abc.com/upload"
querystring = {"ft":"1","fn":"filename"}
payload = ""
files={'file': open(r'Users/.../test.zip', 'rb')}
headers_info = {
'content-type': "multipart/form-data; boundary=---12345",
'x-api-service-version': "1.0",
'connection': "Keep-Alive",
'authorization': "Basic XXXXXXX",
'x-file-format': "decrypted",
'cache-control': "no-cache",
}
response = requests.post(url, data = payload , headers=headers_info , params=querystring , files=files)
print response.status_code
print response.text
I tested the api with POSTMAN (chrome extension to test rest API) and it seems to work fine with postman i get a success response and the file is uploaded.
The postman code for python shows :
import requests
url = "abc.com/upload"
querystring = {"ft":"1","fn":"filename"}
payload = ""
headers = {
'content-type': "multipart/form-data; boundary=---12345",
'accept-encoding': "gzip, deflate",
'x-api-service-version': "1.0",
'connection': "Keep-Alive",
'authorization': "Basic XXXXXXX",
'x-file-format': "decrypted",
'cache-control': "no-cache",
'postman-token': "XXXXXXX"
}
response = requests.request("POST", url, data=payload, headers=headers, params=querystring)
print(response.text)
Any suggestions for the same ? Am I missing something obvious? Thanks for any pointers you can share!
You don't have to specify 'content-type': "multipart/form-data; boundary=---12345", as well as empty data. Try to send request without headers
response = requests.post(url, params=querystring , files=files)
If you fail you might try to add 'authorization': "Basic XXXXXXX", 'postman-token': "XXXXXXX" headers

dart BrowserClient - how to read response headers?

I don't manage to read response headers using browser_client.dart :
import 'package:http/browser_client.dart';
var response =
await client.post(url, headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}, body: body);
print('Response headers: ${response.headers}');
Thanks for your help.
The server needs to allow the browser to expose the headers by listing the headers in the Access-control-expose-headers response header, otherwise you can see them in the browser devtools but when you try to read them in code, the browser will suppress them.
See also
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
Why is Access-Control-Expose-Headers needed?

Resources