Anurag Jain
Anurag Jain

Reputation: 1389

QPX Express Airfare API return The remote server returned an error: (400) Bad Request

I am using QPX Express Airfare API for purpose of getting airline fare in JSON format so I enabled QPX Express Airfare API via google developer console then generate API key accordingly.

I test my api key & json request via QPX Express demo . its working fine but I got exception in my code. I mentioned exception below.

 An exception of type 'System.Net.WebException' occurred in System.dll but was not handled in user code

 Additional information: The remote server returned an error: (400) Bad Request

I am referring this link :

https://developers.google.com/qpx-express/v1/trips/search

code :

    var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://www.googleapis.com/qpxExpress/v1/trips/search?key=AIzaSyBuCQkshTNNDbMidIPzzLofG8Q-izi1PNA");
    httpWebRequest.ContentType = "text/json";
    httpWebRequest.Method = "POST";

    using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
    {
        //string json = "{\"user\":\"test\"," +
        //              "\"password\":\"bla\"}";

        string json = new JavaScriptSerializer().Serialize(new
            {
                origin = "LAS",
                destination="LAX",
                date="2015-04-30",
                adultCount="1",
                infantInLapCount="0",
                infantInSeatCount="0",
                childCount="0",
                seniorCount="0",
                solutions="20",
                refundable = "false"
            });

        streamWriter.Write(json);
        streamWriter.Flush();
        streamWriter.Close();
    }

    var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
    {
        var result = streamReader.ReadToEnd();
    }

Upvotes: 0

Views: 609

Answers (1)

Aleksandr Ivanov
Aleksandr Ivanov

Reputation: 2786

Usually when you get 400 status code from API, that means that your request is not well formed. It's always a good idea to first execute requests in some tool like Fiddler. With your sample you will get a response:

{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "badRequest",
    "message": "Invalid inputs: received empty request."
   }
  ],
  "code": 400,
  "message": "Invalid inputs: received empty request."
 }
}

You can always use anonymous objects but you also should consider creating models. It's really simple with services like json2csharp.com. So your request model can be:

public class Passengers
{
    public string kind { get; set; }
    public int? adultCount { get; set; }
    public int? childCount { get; set; }
    public int? infantInLapCount { get; set; }
    public int? infantInSeatCount { get; set; }
    public int? seniorCount { get; set; }
}

public class PermittedDepartureTime
{
    public string kind { get; set; }
    public string earliestTime { get; set; }
    public string latestTime { get; set; }
}

public class Slouse
{
    public string kind { get; set; }
    public string origin { get; set; }
    public string destination { get; set; }
    public string date { get; set; }
    public int? maxStops { get; set; }
    public int? maxConnectionDuration { get; set; }
    public string preferredCabin { get; set; }
    public PermittedDepartureTime permittedDepartureTime { get; set; }
    public List<string> permittedCarrier { get; set; }
    public string alliance { get; set; }
    public List<string> prohibitedCarrier { get; set; }
}

public class Request
{
    public Passengers passengers { get; set; }
    public List<Slouse> slice { get; set; }
    public string maxPrice { get; set; }
    public string saleCountry { get; set; }
    public bool? refundable { get; set; }
    public int? solutions { get; set; }
}

public class RootObject
{
    public Request request { get; set; }
}

I only changed all value types to nullable types. And now you can create valid request:

var request = new RootObject
{
    request = new Request
    {
        passengers = new Passengers
        {
            adultCount = 1
        },
        slice = new List<Slouse>
        {
            new Slouse
            {
                origin = "LAS",
                destination = "LAX",
                date = "2015-04-30"
            }
        },
        solutions = 20,
        refundable = false
    }
};

If you do not have any restrictions I suggest you to use JSON.NET for JSON serialization and HttpClient for making web requests:

string requestJson = JsonConvert.SerializeObject(request, 
    Formatting.Indented, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });



using (var httpClient = new HttpClient())
{
    var content = new StringContent(requestJson, Encoding.UTF8, "application/json");
    var response = httpClient.PostAsync(url, content).Result;
    var res = response.Content.ReadAsStringAsync().Result;
}

You should probably also create a model for response and deserialize it using JSON.NET.

Upvotes: 1

Related Questions