I am integrating amadeus flight search api and getting error while using access_token. I guess problem is at retrieving the access token?
{ "errors": [ { "code": "38191", "title": "Invalid HTTP header", "detail": "Missing or invalid format for mandatory Authorization header", "status": "401" } ] }
I need to get all the flights from source to destination with price details.
$curls = curl_init();
curl_setopt($curls, CURLOPT_URL, 'https://test.api.amadeus.com/v1/security/oauth2/token');
curl_setopt($curls, CURLOPT_POST, true);
curl_setopt($curls, CURLOPT_POSTFIELDS, "grant_type=client_credentials&client_id=$secretid&client_secret=$secretkey");
curl_setopt($curls, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
$token = curl_exec($curls);
$data = json_decode($token,true);
curl_setopt($curls, CURLOPT_URL, 'https://test.api.amadeus.com/v2/shopping/flight-offers?originLocationCode=SYD&destinationLocationCode=BKK&departureDate=2020-10-01&returnDate=2020-08-05&adults=2&includedAirlineCodes=TG&max=3');
curl_setopt($curls, CURLOPT_HTTPHEADER, array('Authorization: Bearer' .$data['access_token']));
$result = curl_exec($curls);
if (curl_errno($curls)) {
echo 'Error:' . curl_error($curls);
}
//print_r ($result);
curl_close ($curls);
I found a few mistakes in your code and fixed it to make it work:
curl_setopt($curls, CURLOPT_RETURNTRANSFER, true);
to make sure it doesn't only print the API response but returns it as well (please see this post)array('Authorization: Bearer ' .$data['access_token']));
https://test.api.amadeus.com/v2/shopping/flight-offers?originLocationCode=EWR&destinationLocationCode=MIA&departureDate=2020-09-10&returnDate=2020-09-17&adults=1&max=1
. Please take a look at the API reference documentation to understand the different query parameters you can use.CURLOPT_POST
to false (as the API you are trying to call is a GET
)Find below the full example:
$curls = curl_init();
curl_setopt($curls, CURLOPT_URL, 'https://test.api.amadeus.com/v1/security/oauth2/token');
curl_setopt($curls, CURLOPT_POST, true);
curl_setopt($curls, CURLOPT_POSTFIELDS, "grant_type=client_credentials&client_id=$secretid&client_secret=$secretkey");
curl_setopt($curls, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($curls, CURLOPT_RETURNTRANSFER, true);
$token = curl_exec($curls);
$data = json_decode($token,true);
curl_setopt($curls, CURLOPT_URL, 'https://test.api.amadeus.com/v2/shopping/flight-offers?originLocationCode=EWR&destinationLocationCode=MIA&departureDate=2020-09-10&returnDate=2020-09-17&adults=1&max=1');
curl_setopt($curls, CURLOPT_POST, false);
curl_setopt($curls, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' .$data['access_token']));
$result = curl_exec($curls);
if (curl_errno($curls)) {
echo 'Error:' . curl_error($curls);
}
print_r ($result);
curl_close ($curls);
Note: I am not a PHP expert, I am sure the code can be improved.