Search code examples
javascriptoauth-2.0axiosaccess-tokenamadeus

Amadeus API authorization request failing because "Mandatory grant_type form parameter missing"


I am trying to request an authorization token from Amadeus using axios by following this documentation. However, I'm quite unexperienced with the axios library and am failing to build the request correctly, because I get this response:

code: 38187
error: "invalid_request"
error_description: "Mandatory grant_type form parameter missing"
title: "Invalid parameters"

The curious thing is that I tried to simulate the same request with curl and it worked, so I'm really puzzled as to where my error is. Below is my curl request

curl -v "https://test.api.amadeus.com/v1/security/oauth2/token"
     -H "Content-Type: application/x-www-form-urlencoded"
     -d "grant_type=client_credentials&client_id=xxxxxx&client_secret=xxxxxx"

Here is my JavaScript code, please let me know if you are able to notice the difference! Thanks in advance

async getAmadeusKey() {
    const response = await axios({
        url: "https://test.api.amadeus.com/v1/security/oauth2/token",
        method: 'post',
        headers: {
            'Content-Type': 'x-www-form-urlencoded'
        },

        data: {
            grant_type: 'client_credentials',
            client_id: CLIENT_ID,  // of course both these constants are defined outside of this scope
            client_secret: CLIENT_SECRET,
        }
    });
    console.log(response.data);
}

Edit: I had an error with the header, but the response misidentified the error on my request even after applying the fix suggested below. Note that the header should have Content-Type application/x-www-form-urlencoded


Solution

  • By default, axios serialises the data parameter as JSON. Since you want to send a x-www-form-urlencoded request, you will have to serialize the data parameter in that format instead.

    If you're targeting modern browsers only, you can use URLSearchParams like so:

    const data = new URLSearchParams({
      grant_type: 'client_credentials',
      client_id: CLIENT_ID,
      client_secret: CLIENT_SECRET
    })
    
    const response = await axios({
      ... // your code here
      data,
    })