1

I have set AWS Usage Plan and attached a key to the API.

I have this code which throws 403 Forbidden.

fetch(myapi, {
        method: 'GET',
        headers: {
        'Content-Type': 'application/json',
        'x-api-key': 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
        }
    })
    .then(function(response) {
                             return response.json();
      })
    .then(function(json) {
                             return json;
      });

where as when I run Curl with the same key on the same api, it returns 200 OK.

curl -i -H "x-api-key:xxxxxxxxxxxxxxxxxxxxxx" -X GET https://xxxxxxxx.execute-api.us-east-1.amazonaws.com/Stage/test.

What is going wrong with the Fetch API code?

2 Answers 2

2

If this fetch API call is being done in the browser then you might want to check if OPTIONS is also requiring an API key. I encountered this before where I could also curl and run the API via postman. Try doing a curl call to OPTION without the x-api-key and see if you get an error. If there is an error, you need to add the x-api-key when OPTIONS is being called or you can disable it in API gateway. You can follow this for reference to disable it.

Just set API Key Required to false

0

As per AWS docs make sure your fetch url is set correctly to the following parameters https://{api_id}.execute-api.{region}.amazonaws.com/{stage_name}/{resource_name}

The following headers should be enough as well:

    headers: {
        'x-api-key': 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
    }

Here a snipped generated with Postman:

    var myHeaders = new Headers();
    myHeaders.append("x-api-key", "myApiKey");

    var requestOptions = {
      method: 'GET',
      headers: myHeaders,
      redirect: 'follow'
    };

    fetch("https://1234567889.execute-api.us-east-1.amazonaws.com/myStageName/MyEndpoint", requestOptions)
      .then(response => response.text())
      .then(result => console.log(result))
      .catch(error => console.log('error', error));

Not the answer you're looking for? Browse other questions tagged or ask your own question.