PHP POST request to flight API returns 405 Method Not Allowed error

I’m working with a travel booking API and trying to create a new search session using PHP. The API should return a location header in the response that I need for subsequent requests, but I keep getting a 405 Method Not Allowed error instead.

Here’s my current code:

require_once 'vendor/autoload.php';
require_once 'vendor/mashape/unirest-php/src/Unirest.php';

$apiResponse = Unirest\Request::post("https://travel-api-service.p.rapidapi.com/flights/search/v2.0",
  array(
    "X-RapidAPI-Host" => "travel-api-service.p.rapidapi.com",
    "X-RapidAPI-Key" => "your-api-key-here",
    "Content-Type" => "application/x-www-form-urlencoded"
  ),
  array(
    "departureDate" => "2024-06-15",
    "travelClass" => "economy",
    "childCount" => 0,
    "infantCount" => 0,
    "countryCode" => "US",
    "currencyCode" => "USD",
    "localeCode" => "en-US",
    "fromAirport" => "LAX-sky",
    "toAirport" => "JFK-sky",
    "returnDate" => "2024-06-20",
    "passengerCount" => 2
  )
);

var_dump($apiResponse);

I expect to get headers like this:

cache-control: private
content-type: application/json
date: Thu, 15 Jun 2024 10:30:45 GMT
location: http://api.travel-service.net/flights/search/us1/v2.0/abc123-def456-ghi789
server: RapidAPI-1.0.20

But instead I’m getting a 405 error. The response shows Method Not Allowed but I’m sure I’m using POST correctly. Has anyone encountered this issue before? What could be causing this problem?

Had the same problem with travel APIs. You’re probably sending form data but telling the API it’s something else. Switch to JSON - that’s what most APIs want for POST requests. Use json_encode() on your data and set the content type to “application/json”. Also check the docs again - some search endpoints actually want GET with query params, not POST with body data.

That 405 error means the endpoint won’t take POST requests, even if the docs say it should. I’ve hit this same issue with RapidAPI flight services before. Switch to GET and put your parameters in the query string instead of the request body. Most flight search APIs actually use GET for searches anyway, weird as that sounds. Also check your endpoint URL - there might be version differences or regional variants that only work with certain methods. If GET fails too, double-check the exact endpoint path in RapidAPI’s console. The working endpoint might be different from what’s documented.

check if that endpoint actually takes post requests - some apis are picky about methods. try droping the content-type header completely, or switch from form-urlencoded to application/json. the server might be getting confused by the current setup.