xampper
xampper

Reputation: 77

Google QPX Express API PHP

I'm trying to use QPX Express API for my website to search for flights.

https://developers.google.com/qpx-express/v1/requests#Examples

I have no idea how to run

curl -d @request.json --header "Content-Type: application/json" https://www.googleapis.com/qpxExpress/v1/trips/search?key=xxxxxxxxxxxxxx

from my php file. And how should I manage the json file. I quess I should make a php file and set the header type, am I correct?

I could not find anything from anywhere

Upvotes: 4

Views: 2067

Answers (1)

Patrick Q
Patrick Q

Reputation: 6393

You do not need to create and save an actual JSON file for each request. You can simply create a JSON string and send that as the POST payload. As far as executing the curl, you should see the native functions available in the PHP Manual. Specifically, curl_init(), curl_setopt(), and curl_exec(). Here's an example...

$url = "https://www.googleapis.com/qpxExpress/v1/trips/search?key=YOUR_API_KEY_HERE";

$postData = '{
  "request": {
    "passengers": {
      "adultCount": 1
    },
    "slice": [
      {
        "origin": "BOS",
        "destination": "LAX",
        "date": "2016-05-10"
      },
      {
        "origin": "LAX",
        "destination": "BOS",
        "date": "2016-05-15"
      }
    ]
  }
}';

$curlConnection = curl_init();

curl_setopt($curlConnection, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
curl_setopt($curlConnection, CURLOPT_URL, $url);
curl_setopt($curlConnection, CURLOPT_POST, TRUE);
curl_setopt($curlConnection, CURLOPT_POSTFIELDS, $postData);
curl_setopt($curlConnection, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($curlConnection, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curlConnection, CURLOPT_SSL_VERIFYPEER, FALSE);

$results = curl_exec($curlConnection);

You could also use an array to create the payload, and then use json_encode() to convert it into a JSON string.

$postData = array(
    "request" => array(
        "passengers" => array(
            "adultCount" => 1
        ),
        "slice" => array(
            array(
                "origin" => "BOS",
                "destination" => "LAX",
                "date" => "2016-05-10"
            ),
            array(
                "origin" => "LAX",
                "destination" => "BOS",
                "date" => "2016-05-15"
            )
        )
    )
);

And then use

curl_setopt($curlConnection, CURLOPT_POSTFIELDS, json_encode($postData));

Upvotes: 4

Related Questions