About Amadeus Self-Service APIs

Amadeus Self-Service travel APIs connect you to data and services you can use to build high-quality travel apps. The APIs offer flight search, hotel search, booking capabilities and even AI-powered travel insights to help users through their journey with a complete end-to-end experience. In this article we’ll focus on demonstrating the popular Flight Offers Search API with PHP code. The techniques shown here will give you the base for using any of the other APIs in the Self-Service catalog.

OAuth2 authentication

Amadeus Self-Service APIs use OAuth2 for authentication. If you’re familiar with the OAuth2 authentication process, you have a great head start. If you’re new to OAuth2, no problem: it’s straightforward and used by many APIs and web services. Check out our Authorization Guide for a full walk-through of the process.

Steps to using Amadeus Self-Service APIs in PHP

Now that you know something about OAuth2, you’re ready to start using Amadeus Self-Service APIs in PHP. Here are the steps we’ll take to demonstrate this process:

  1. Registering with Amadeus for Developers.
  2. Creating a new app with Self-Service APIs.
  3. Obtaining an API key and an API secret.
  4. Setting up a PHP development environment.
  5. Writing the PHP script to request an access token.
  6. Writing the PHP script to consume the Flight Offers Search API.

First, create an account on the Amadeus for Developers portal. Then, sign in to your account and create a new app on the My Self-Service Workspace. Next, obtain the API Key and API Secret linked to your newly created app. Your PHP app (the OAuth2 client) will use the API Key and API Secret values as its client credentials to request an access token from an Amadeus authorization server to access any Self-Service API.

Setting up your PHP development environment

To interact with Amadeus Self-Service APIs, your PHP app must have the capability to implement HTTP requests. You could write the code to add that capability to your PHP app, but it makes more sense to use the Requests package, which provides useful helper functions.

To download and install Requests, you can use Composer, a PHP dependency-management tool that lets you declare the libraries your project depends on. Once Composer is set up, installing Requests using Composer is just a matter of running the following command in a terminal:

composer require rmccue/requests

Note the location of the requests folder that contains the Requests library and its associated files after the installation, for example, path/requests.

Requesting an access token

When your PHP development environment is Requests-ready, you can write a script to request an access token from the Amadeus authorization server. Open a new PHP file in your favorite editor, then add the following code:

Start by loading requests:

​require_once 'path/requests/library/Requests.php';

Then register an autoloader:

Requests::register_autoloader();

You register an autoloader so Requests can autoload its internal classes on demand at runtime. Autoloading is the process of automatically loading PHP classes without explicitly including them in your PHP scripts. To request an access token, first prepare a POST request to be sent to the authorization server:

​$url = 'https://test.api.amadeus.com/v1/security/oauth2/token';

We’ll include the following parameters in the request body and set the Content-Type header:

​$auth_data = array(
'client_id' => 'API Key',
'client_secret' => 'API Secret',
'grant_type'    => 'client_credentials'
);
$headers = array('Content-Type' => 'application/x-www-form-urlencoded');

Then we’ll send the request to the authorization server:

​$requests_response = Requests::post($url, $headers, $auth_data);

The authorization server will return a Requests_Response object. Use this code to peek into the body property of the Requests_Response object:

​$response_body = json_decode($requests_response->body);
echo '<pre&>', json_encode($response_body, JSON_PRETTY_PRINT), '</pre>';

If the authorization is granted, the body property of the Requests_Response object will contain a string that reads like:

{
  "type": "amadeusOAuth2Token",
  "username": "your username",
  "application_name": "Your application name",
  "client_id": "API Key",
  "token_type": "Bearer",
  "access_token": "f6lBVRBa4gDABw9gh7ybv65VxBRk",
  "expires_in": 1799,
  "state": "approved",
  "scope": ""
}

You can extract and store that access token value and use it to call an Amadeus Self-Service API:

​$access_token = $response_body->access_token;

If the authorization fails, the body property of the Requests_Response object will instead contain the error information, such as:

{
  "error": "invalid_client",
  "error_description": "Client credentials are invalid",
  "code": 38187,
  "title": "Invalid parameters"
}

Putting the pieces together gives you the complete PHP script to request an access token:

&lt;?php
// Loading Requests
require_once 'path/requests/library/Requests.php';
// Registering an autoloader
Requests::register_autoloader();
// Preparing the request message
$url = 'https://test.api.amadeus.com/v1/security/oauth2/token';
$auth_data = array(
'client_id' =&gt; 'API Key',
'client_secret' =&gt; 'API Secret',
'grant_type' =&gt; 'client_credentials'
);
$headers = array('Content-Type' =&gt; 'application/x-www-form-urlencoded');
try {
// Sending the request message by POST
$requests_response = Requests::post($url, $headers, $auth_data);
// Server returns a Requests_Response object
echo 'Response from the authorization server:';
$response_body = json_decode($requests_response-&gt;body);
echo '&lt;pre&gt;', json_encode($response_body, JSON_PRETTY_PRINT), '&lt;/pre&gt;';
if(property_exists($response_body, 'error')) die;
// Extract and store the access token
$access_token = $response_body-&gt;access_token;
} catch (Exception $e) {
print_r($e-&gt;getMessage());
}

Consuming the Flight Offers Search API

Once your app receives an access token from the authorization server, use it to call the Flight Offers Search API to get flight offers for a journey. For this example, we’ll search for a flight from Boston to Paris, departing on 14 Feb, 2020, for two adults.

If you look at the Flight Offers Search API documentation, you’ll find the endpoint is at:
https://test.api.amadeus.com/v2/shopping/flight-offers

The parameters required to call the Flight Offers Search API include:

  • originLocationCode, the location code of the place of departure as specified in the city/airport IATA code. In this case, BOS for Boston.
  • destinationLocationCode, the location code of the place of arrival as specified in the city/airport IATA code. In this case, PAR for Paris.
  • departureDate, the date of departure as specified in the ISO 8601 YYYY-MM-DD format. In this case, 2020-02-14.
  • adults, the number of adult travelers (aged 12 or older).

To set the Flight Offers Search API endpoint, let’s add some code to our PHP file:

​$endpoint = 'https://test.api.amadeus.com/v2/shopping/flight-offers';

Gather the travel details:

​$travel_data = array(
  'originLocationCode'     => 'BOS',
  'destinationLocationCode' => 'PAR',
  'departureDate'           => '2020-02-14',
  'adults'                  => 2
);

Generate a URL-encoded query string:

​$params = http_build_query($travel_data);

Now construct the URL:

​$url = $endpoint.'?'.$params;

And don’t forget to include your previously obtained access token in the HTTP header:

​$headers = array('Authorization' => 'Bearer '.$access_token);

Now make an API call using GET:

​$requests_response = Requests::get($url, $headers);

The Flight Offers Search API server will return a Requests_Response object. Use this code to peek into the body property of the Requests_Response object:

​$response_body = json_decode($requests_response->body);
echo '<pre>', json_encode($response_body, JSON_PRETTY_PRINT), '</pre>';

If the call to the Flight Offers Search API is successful, the body property of the Requests_Response object will contain the details of all flights from Boston to Paris departing on 14 Feb 2020 for two adults. Here’s an example of the JSON encoded response:

​"meta": {
    "count": 171,
    "links": {
        "self": "https://test.api.amadeus.com/v2/shopping/flight-offers?originLocationCode=BOS&destinationLocationCode=PAR&departureDate=2020-02-14&adults=2"
    }
},
"data": [
    {
        "type": "flight-offer",
        "id": "1",
        "source": "GDS",
        "instantTicketingRequired": false,
        "nonHomogeneous": false,
        "oneWay": false,
        "lastTicketingDate": "2019-12-08",
        "numberOfBookableSeats": 6,
        "itineraries": [
            {
                "duration": "PT13H20M",
                "segments": [
                    {
                        "departure": {
                            "iataCode": "BOS",
                            "terminal": "E",
                            "at": "2020-02-14T21:35:00"
                        },
                        "arrival": {
                            "iataCode": "LIS",
                            "terminal": "1",
                            "at": "2020-02-15T10:40:00"
                        },
                        "carrierCode": "S4",
                        "number": "220",
                        "aircraft": {
                            "code": "321"
                        },
                        "operating": {
                            "carrierCode": "S4"
                        },
                        "duration": "PT8H5M",
                        ...
                    },
                    ...
                ]
            }
        ],
        "price": {
            "currency": "EUR",
            "total": "734.86",
            "base": "612.00",
            "fees": [
                ...
            ],
            "grandTotal": "734.86"
        },
        ...
        "travelerPricings": [
            {
                "travelerId": "1",
                "fareOption": "STANDARD",
                "travelerType": "ADULT",
                "price": {
                    "currency": "EUR",
                    "total": "367.43",
                    "base": "306.00"
                },
                ...
            },
            {
                "travelerId": "2",
                "fareOption": "STANDARD",
                "travelerType": "ADULT",
                "price": {
                    "currency": "EUR",
                    "total": "367.43",
                    "base": "306.00"
                },
                ...
            }
        ]
    },
    {
        "type": "flight-offer",
        "id": "2",
        "source": "GDS",
        "instantTicketingRequired": false,
        "nonHomogeneous": false,
        "oneWay": false,
        "lastTicketingDate": "2019-12-08",
        "numberOfBookableSeats": 6,
        "itineraries": [
            {
              "duration": "PT16H10M",
              ...

Briefly, the above response from the Flight Offers Search API tells us that the number of flights that meet the requirements of the journey is 171:

​"meta": {
    "count": 171,
    ...
},

The duration of the first flight offer (“id”: “1”) that appears in the response is 13 hours and 20 minutes:

​"duration": "PT13H20M"

The flight departs from Boston at 21:35 hours from terminal E:

​"departure": {
    "iataCode": "BOS",
    "terminal": "E",
    "at": "2020-02-14T21:35:00"
},

The flight arrives in Paris at 1040 hours at Terminal 1:

​"arrival": {
    "iataCode": "LIS",
    "terminal": "1",
    "at": "2020-02-15T10:40:00"
},

The total price for the first traveler (“travelerId”: “1”) at the standard adult fare is 367.43 euros:

​"travelerId": "1",
"fareOption": "STANDARD",
"travelerType": "ADULT",
"price": {
    "currency": "EUR",
    "total": "367.43",
    "base": "306.00"
},

When you put the pieces together, you have the complete PHP script to call the Flight Offers Search API to obtain flight offers on a given journey:

if(isset($access_token)){
// Setting the Flight Offers Search API endpoint
$endpoint = 'https://test.api.amadeus.com/v2/shopping/flight-offers';
// Gathering the travel details
$travel_data = array(
'originLocationCode' =&gt; 'BOS',
'destinationLocationCode' =&gt; 'PAR',
'departureDate' =&gt; '2020-02-14',
'adults' =&gt; 2
);
// Generating URL-encoded query string
$params = http_build_query($travel_data);
$url = $endpoint.'?'.$params;
// Including your previously obtained access token in the HTTP header
$headers = array('Authorization' =&gt; 'Bearer '.$access_token);
try {
// Making API call to the Flight Offers Search API using GET
$requests_response = Requests::get($url, $headers);
echo 'Response from the Flight Offers Search API:';
$response_body = json_decode($requests_response-&gt;body);
echo '&lt;pre&gt;', json_encode($response_body, JSON_PRETTY_PRINT), '&lt;/pre&gt;';
if(property_exists($response_body, 'error')) die;
} catch (Exception $e) {
print_r($e-&gt;getMessage());
}
}

Summary

So far so good! Moving forward, you can simply include the first PHP script in any PHP file that needs to request an access token from the Amadeus authorization server and make the second PHP script into a function that takes an API endpoint and parameters as its arguments. In this way, accessing and calling any Self-Service API is just a matter of calling that function and passing it the endpoint and parameters of that API.

You can find the endpoints and the parameters of the different Self-Service APIs in the Self-Service APIs documentation.

This article was originally published on Amadeus’s blog.

How to work with us

  • Contact us to set up a call.
  • We will analyze your needs and recommend a content contract solution.
  • Sign on with ContentLab.
  • We deliver topic-curated, deeply technical content to you.

To get started, complete the form to the right to schedule a call with us.

Send this to a friend