Amadeus flight API authorization - flutter

I am trying to use one of the Amadeus flight API (flight lowest-fare search) and I think I am having issues with the authorization. The first part of the authorization works fine where I have to input the grant type, API key, and API secret. This returns the access token needed to return the flight API. However, when printing the response body I keep getting null. Could someone help me with this? I am showing my API key and API secret but that's not an issue as I can create a new one. Here's the code:
To first provide context, here's how an Amadeus API gets called after access token is retrieved from the authorization server. This endpoint returns a flight's check-in links.
curl -X GET \
"https://test.api.amadeus.com/v2/reference-data/urls/checkin-links?airlineCode=1X" \
-H "Authorization: Bearer CpjU0sEenniHCgPDrndzOSWFk5mN"
I believe my issue might in my authorization header in the flight low-fare search endpoint. I concatenated the two variables in which the token_type which has a value of 'Bearer' and the access token. In the curl example, 'Bearer' is within the speech marks. In flutter, you cannot do that as 'Authorization is the only header. Below is my code in dart:
getFlights(fromCode, toCode) async {
// getting access token
var response = await http.post(
'https://test.api.amadeus.com/v1/security/oauth2/token',
body: {
"grant_type": "client_credentials",
"client_id": "cxuxBmIvbpbv0JKzKTsJjNqc595uJVYb",
"client_secret": "buhj4SDGVrG1AzzV",
},
);
if (response.statusCode == 200) {
try {
print(response.body);
var code = jsonDecode(response.body);
if (code != null) {
var tokenType = code['token_type'];
print(tokenType);
print(code['access_token']);
var token = code['access_token'];
var bearerToken = '$tokenType ' + '$token';
print(bearerToken);
// flight low-fare search endpoint
var flightApi = await http.get(
'https://test.api.amadeus.com/v1/shopping/flight-offers?origin=LHR&destination=CDG&departureDate=2020-03-19&max=2',
headers: {
"Authorization": bearerToken,
});
var flight = json.decode(response.body);
print(flight['data']);
}
} catch (e) {
print(e.toString());
}
}
}
This the return from the authorization server which provides the access token:
{
"type": "amadeusOAuth2Token",
"username": "I REMOVED THIS",
"application_name": "I REMOVED THIS",
"client_id": "cxuxBmIvbpbv0JKzKTsJjNqc595uJVYb",
"token_type": "Bearer",
"access_token": "z8rVGOAuGaXGNUMIcVPYW76ki5Dl",
"expires_in": 1799,
"state": "approved",
"scope": ""
}
This is the return for the flight low-fare search endpoint
flutter: null

Related

When making a request to the Vision API Product Search an error occurs "message": "The request is missing a valid API key."

When I register a service account for the Vision API Product Search there's a json file downloaded into my desktop that has the private key. However, when making a request into this api there's no place to send that JSON. I'll show you the documentation and my code.
I didn't understand also what is the curl request and how to send it using the http post request.
And This is my code:
Future<void> uploadProductSet() async {
var projectId = 'estoOne';
var locationId = 'europe-west1';
var url = 'https://vision.googleapis.com/v1/projects/$projectId/locations/$locationId/productSets';
final responseOne = await http
.post(Uri.parse(url),
body: json.encode({
'displayName': 'Product-Set-One',
}))
.catchError((error) {
throw error;
});
print(resoinseOne.body);
}
You have to send your access token with the Authorization header.
The API seems to use the Bearer authentication method.
So set the following header in your http request: Bearer $authToken
You should get the auth-token from the credentials file you've downloaded
So your code should look something like this: (untested)
await http.post(Uri.parse(url),
headers: { 'Authorization': 'Bearer $authToken' },
body: json.encode({
'displayName': 'Product-Set-One',
})).catchError((error) {
throw error
})

Flutter qraphQl issue with setting requesting data from body of api

I am trying to connect to an graphQl api that uses the token as the password in the Basic auth section of the header. I have tried using flutter_graphql but as I only get the token back after the user logs in. I have managed to get logged in using:
String username = "";
String password = token;
String basicAuth = 'Basic' + base64Encode(utf8.encode("$username:$password"));
String projects = "query Projects{Projects{id name}}";
Uri newUri = Uri.parse("$link");
var newResponse = await http.post(newUri, headers: {
"Authorization": basicAuth,
"Content-Type": "application/graphql"
}, body: //I need to get projects here.
);
var newNonJsonData = newResponse.body;
group("Testing the graph ql data after logging in: ", () {
test("Logged in", () {
expect(newResponse.statusCode, 200);
});
test("getting the data from the api", () {
print("non json return:" + newNonJsonData);
});
});
I have tried to set the body as
jsonEncode({
'query' : prjects
})
but the moment I request the data it asks to log in.
Please could someone help!!!

Stripe Metadata submission invalid object

I am implementing Stripe payments, but am unable to submit metadata as a query param as per the documentation, it seems as though it wants iterable stringified key-value pairs which I have tried to achieve with the below with no luck.
Question: How can I pass metadata to Stripe using Dart and the HTTP library?
class StripeServices {
static var client = http.Client();
static var stripeTestKey =
'privatesecretkeyfromstripe';
static Future<void> createStripeCustomer() async {
Map<String, String> metadata = {'uuid': '123456'};
Uri uri = Uri(
scheme: 'https',
host: 'api.stripe.com',
path: '/v1/customers',
queryParameters: {
'description': 'Test Customer',
'metadata': metadata.entries.toList().toString()
});
var response = await client.post(
uri,
headers: {
'Authorization': 'Bearer ' + stripeTestKey,
},
);
print(response.body);
}
The error I am getting back from the endpoint is
> flutter: { "error": {
> "message": "Invalid object",
> "param": "metadata",
> "type": "invalid_request_error" } }
calling Stripe API requires a secret API key, and you shouldn't store and use the API key in your frontend application because it's not safe.
Instead you should make the API call from your backend where the API key can be securely stored.

GraphQL query to GitHub failing with HTTP 422 Unprocessable Entity

I am currently working on a simple GitHub GraphQL client in NodeJS.
Given that GitHub GraphQL API is accessible only with an access token, I set up an OAuth2 request to grab the access token and then tried to fire a simple GraphQL query.
OAuth2 flow gives me the token, but when I send the query, I get HTTP 422.
Here below simplified snippets from my own code:
Prepare the URL to display on UI side, to let user click it and perform login with GitHub
getGitHubAuthenticationURL(): string {
const searchParams = new URLSearchParams({
client_id,
state,
login,
scope,
});
return `https://github.com/login/oauth/authorize?${searchParams}`;
}
My ExpressJs server listening to GitHub OAuth2 responses
httpServer.get("/from-github/oauth-callback", async (req, res) => {
const {
query: { code, state },
} = req;
const accessToken = await requestGitHubAccessToken(code as string);
[...]
});
Requesting access token
async requestToken(code: string): Promise<string> {
const { data } = await axios.post(
"https://github.com/login/oauth/access_token",
{
client_id,
client_secret,
code
},
{
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
}
);
return data.access_token;
}
Firing simple graphql query
const data = await axios.post(
"https://graphql.github.com/graphql/proxy",
{ query: "{ viewer { login } }"},
{
headers: {
Authorization: `Bearer ${accessToken}`,
"Content-Type": "application/json",
},
}
);
Do you guys have any clue?
Perhaps I am doing something wrong with the OAuth2 flow? As in most of the examples I found on the web, a personal token is used for this purpose, generated on GitHub, but I would like to use OAuth2 instead.
Thanks in advance for any help, I really appreciate it!
EDIT
I changed the query from { query: "query { viewer { login } }"} to { query: "{ viewer { login } }"}, nonetheless, the issue is still present.
I finally found the solution:
Change the URL from https://graphql.github.com/graphql/proxy to https://api.github.com/graphql, see here
Add the following HTTP headers
"Content-Type": "application/json"
"Content-Length"
"User-Agent"
Hope this will help others out there.

Node Js Restapi - Calling Post Method in Flutter Doesn't Work

I have local api and jwt by node js i want to send my username and password from flutter and send it to node js to give me this token and later i will save it in local storage but when i tell flutter post to the api doesn't post
my code :
You can use http method here like below Future example
Future postContact(access_token,name,email,phone,message) async {
String apiUrl = '$_apiUrl/user/contact-us';
http.Response response = await http.post(apiUrl,headers: {
"Accept": "application/json",
"Accesstoken": "Bearer $access_token"
}, body: {'name':'$name','email':'$email','phone':'$phone','message':'$message'});
print("Result: ${response.body}");
return json.decode(response.body);
}