I am trying to implement Auto search in Angular 2. I am trying to get data from API to populate in suggestion list. My API accepts headers with token. Below is a sample url:
curl -X GET --header 'Accept: application/json' --header 'Authorization: USERNAME PASSWORD' 'https://apsapi.azurewebsites.net/api/searchusers?searchstring=anil'
I am using npm ng2-completer plugin. This is my API Call:
constructor(private completerService: CompleterService, private translationService: AppTranslationService, private alertService: AlertService, private useronboardService: UserOnboard)
{
let options = new RequestOptions({ headers: new Headers() });
options.headers.set("Authorization",'Bearer0l4B9VpOnJMBzxMee8SQdU8pFW_L8wBAyQ');
let url = "https://arsapi.azurewebsites.net/api/searchusers?searchstring="
this.dataService = completerService.remote(url, 'userName', 'userName');
this.dataService.requestOptions(options);
}
I do not see any header attached in request. Below is image.
image
Above piece of code results in error and it tells: (method)RemoteData.requestoptions(requestOptions:any):void (TS)Expected 1 arguments but got 2.
Can someone help me to add header in the above code?
Related
I'm trying to execute the following curl in dart but I can't find a way to achieve that:
curl --location --request GET 'https://someurl.com/query' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer xxxx' \
--data-raw '{
"query":"test_value",
"size":10
}'
The only way I've found to achieve this is to use POST and put the raw data inside the body but I was wondering if there is a real way to achieve that since the POST request with a body seems to be about 220ms slower than the GET one(I know that they should be almost equal, it may be something from the server when recieving the request).
The default get() method of the http package doesn't allow you to add data since that isn't a common thing to do. You can get around this by using the Request object directly for more fine-grained control, as stated in the docs:
Request req = Request('GET', Uri.parse('https://someurl.com/query'))
..body = json.encode(data)
..headers.addAll({
"Content-type": "application/json",
"Authorization": "Bearer xxxx"
});
var response await req.send();
if (response.statusCode == 200) {
// do something with valid response
}
I'd look at getting the POST variant working properly, since a GET method semantically shouldn't do anything with the provided body. But that's a different discussion of course.
import 'package:http/http.dart' as http;
// Define the raw data to be sent in the request
String rawData = '{ "key": "value" }';
// Send the GET request with the raw data as the body
http.Response response = await http.get(
'https://example.com/endpoint',
headers: {'Content-Type': 'application/json'},
body: rawData,
);
// Check the status code of the response to see if the request was successful
if (response.statusCode == 200) {
// The request was successful, process the response
} else {
// The request was not successful, handle the error
}
I am new to using this Yodlee tool, I created my developer account, and I am wanting to consume the sandbox APIs.
I am not being able to consume by rest with the Talend Api not even the initial method of "auth" (https://sandbox.api.yodlee.com/ysl/auth/token) to obtain the token; I'm passing the loginName, Api-version: 1.1, and content-type in the header as specified, then the clientId and the secret in the body.
The error message it returns is:
{
"errorCode": "Y303",
"errorMessage": "clientId or secret is missing",
"referenceCode": "rrt-8413800343306027303-c-gce-12663 ....."
}
Maybe the sandbox account doesn't allow me to do this, or am I forgetting something?
I just got the same issue. I am using RestSharp.
Finally found out that's a mismatched Content-Type.
It works after adding the header: Content-Type: application/x-www-form-urlencoded
For anyone having this issue with Google Apps Script, this is how I did it:
/************************************************************************************
*
* This function starts the app, replace variables as necessary
*
************************************************************************************/
function primaryFunction() {
// Declare variables
var yodleeToken = {};
var loginName = "ENTER_LOGIN_NAME";
var clientID = "ENTER_CLIENT-ID";
var clientSecret = "ENTER_CLIENT_SECRET";
var yodleeURL = "https://sandbox.api.yodlee.com/ysl/";
// Generate user token
yodleeToken = getUserToken(loginName, clientID, clientSecret, yodleeURL);
}
/************************************************************************************
*
* Creating function to get user token
*
* #params loginName {String} Login name provided by Yodlee API
* #params clientID {String} Client ID provided by Yodlee API
* #params clientSecret {String} Client Secret provided by Yodlee API
* #params yodleeURL {String} Yodlee API Endpoint
*
* References
* https://av.developer.yodlee.com/
*
************************************************************************************/
function getUserToken(loginName, clientID, clientSecret, yodleeURL) {
// Specify headers
var headers = {
'Api-Version': '1.1',
'Content-Type': 'application/x-www-form-urlencoded',
'loginName': encodeURIComponent(loginName)
};
// Build params
var parameters = {
'method': 'POST',
'headers': headers,
'payload': encodeURI("clientId=" + clientID + "&secret=" + clientSecret),
'redirect': 'follow',
'timeout': 0,
// 'muteHttpExceptions': true,
};
// Call API with params
var response = UrlFetchApp.fetch(yodleeURL + "auth/token", parameters);
var responseJSON = JSON.parse(response);
// return JSON response with Link Token
return responseJSON;
}
You need to pass clientId and secret key in data-urlencode and remaining keys in header then it will return token
curl --location --request POST 'https://sandbox.api.yodlee.com/ysl/auth/token' \
--header 'Api-Version: 1.1' \
--header 'loginName: From your dashboard (Sandbox only)' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'clientId=Your clientId' \
--data-urlencode 'secret=Your secret'
How can I convert the following cURL command to a Postman rest call?
curl -X POST abc.com/input.import
-H 'content-type: application/x-www-form-urlencoded'
--data-urlencode "apiKey=123-456"
--data-urlencode "secret=12/her"
--data-urlencode "userKey=ApUR"
--data-urlencode "email=fakeImportedAccount#example.com"
--data-urlencode "profile={'firstName':'John','lastName':'Kira'}"
I tried the following:
URL: (POST) abc.com/input.import
Header: Content-Type:application/json
Body:
{
"apiKey":"123-456",
"userKey":"ApUR",
"secret":"12/her",
"email":"fakeImportedAccount#example.com",
"profile": {
"firstName":"John",
"lastName":"Kira"
}
}
EDIT: Raw-body format in Postman is required. Import creates the request in "x-www-form-urlencoded" form
The content-type is not application/json, it's application/x-www-form-urlencoded. What you need to do is in the body tab, select application/x-www-form-urlencoded. The content-type header will automatically be set for you. The just start adding the key/value pairs (the --data-urlencoded arguments)
UPDATE
Unrelated, but for those looking for a way to post JSON (which is very common), you would use the "raw" radio button and then you would manually type in the JSON to the window they provide. Also you would set the Content-Type header to application/json.
I finally found: I have to url-encode every key value and send it with Content-Type:application/x-www-form-urlencoded.
Header:application/x-www-form-urlencoded
Body:
{
"apiKey":"123-456",
"userKey":"ApUR",
"secret":"12%2Fher",
"email":"fakeImportedAccount%40example.com",
"profile":{
"firstName":"John",
"lastName":"Kira"
}
}
followed by the access documentation
both are not working by using
Authorization Header
Query Parameter
Using the latest version of loopback 2.1.X.
I turned off the email verification and successfully got the AccessToken object from the initial login. The header and the query request are not working now.
ACCESS_TOKEN=6Nb2ti5QEXIoDBS5FQGWIz4poRFiBCMMYJbYXSGHWuulOuy0GTEuGx2VCEVvbpBK
Authorization Header
curl -X GET -H "Authorization: $ACCESS_TOKEN" \
http://localhost:3000/api/widgets
Query Parameter
curl -X GET http://localhost:3000/api/widgets?access_token=$ACCESS_TOKEN
In header pass key as authorization not ACCESS_TOKEN
In query params pass key as accessToken not access_token
Here is what works for me in Angular 2 :
initRequestOptions(accessToken:any) {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Access-Control-Allow-Origin', '*');
headers.append('Authorization', accessToken);
return new RequestOptions({headers: headers});
}
makeRequest(accessToken:any){
let options = this.initRequestOptions(accessToken);
this.http.get('http://' + apiUrl + '/api/MyModel, options)
.subscribe(
//...
)
}
So basically you need to create a headers object , add an 'Authorization' item whoes value is the access token , and use the headers object to create a RequestOptions object to be inserted in the request.
Also loopback explorer passes the access token as a url encoded parameter so this should work too :
http://localhost:3000/api/MyModel?access_token=X3Ovz4G1PfmPiNGgU5YgORPwPGLaVt9r8kU7f4tu1bDMyA4zbqiUEgeDAC3qkZLR
I have successfully completed the first three steps of the authentication process: step one(authorize), step two (receive redirect ) and step three (get an access token).
But, doing the following request gives me an error:
curl -H 'Authorization: Bearer xxxxoKnAKxxxxxndQNRZgRa0Dxxxxx' 'https://sandbox-api.uber.com/v1/requests'
Response:
{"message":"Not supported","code":"not_found"}
I have the same message with all required params:
curl -H 'Authorization: Bearer xxxxoKnAKxxxxxndQNRZgRa0Dxxxxx' 'https://sandbox-api.uber.com/v1/requests?product_id=5b451799-a7c3-480e-8720-891f2b51abb4&start_latitude=48.869576&start_longitude=2.30825&end_latitude=48.84839&end_longitude=2.395921'
Am I missing something?
Edit:
Ruby version with HTTParty:
def request(bearer, product_id="5b451799-a7c3-480e-8720-891f2b51abb4", start_latitude=48.869576, start_longitude=2.30825, end_latitude=48.84839, end_longitude=2.395921)
parameters = { product_id: product_id,
start_latitude: start_latitude,
start_longitude: start_longitude,
end_latitude: end_latitude,
end_longitude: end_longitude
}
self.class.post('/v1/requests', query: parameters, headers: { "Authorization" => "Bearer #{bearer}", 'Content-Type' => 'application/json' })
end
A GET to 'https://sandbox-api.uber.com/v1/requests' won't work since you need to include a such as https://sandbox-api.uber.com/v1/requests/request_id
A POST to 'https://sandbox-api.uber.com/v1/requests' requires you to post the parameters as part of the JSON body.
Once you have the request ID as part of the response, you will able poll for details using the first command.