That API Guy's - API Forum

API link for searching cat image by breed returns an empty object

The url that is showing in the example page for searching a cat image by the breed, example url: https://api.thecatapi.com/v1/images/search?breed_id=beng returns only an empty object. I’m coding in Vanilla JavaScript and I’m using the fetch() method instead of XMLHttpRequest(); It seems I need to implement the api-key but I’m not quite sure how to add it in.
I know that with XMLHttpRequest(); I can use setRequestHeader(); to add my api-key but I can’t seem to find information on how to do the same with fetch(); Any suggestion or advice would be really appreciate it.

Update: I got it working now!
Like with XMLHttpRequest(); with Fetch(); I had to find a way to implement the api key to the header.
Where with XMLHttpRequest(); the codes looks something similar like this:

var xhr = new XMLHttpRequest();
xhr.open(“GET”, “https://api.thecatapi.com/v1/images/search?breed_id=beng”);

xhr.setRequestHeader(“x-api-key”, “My_API_Key”);

xhr.send(data);

With Fetch() looks something like this:

const url= ‘https://api.thecatapi.com/v1/images/search?breed_id=beng’;

let h = new Headers();

let req = new Request(url, {
method: ‘GET’,
headers: { // I was missing this part right here
“Content-Type”: “application/json”,
“x-api-key”: “My_API_Key” },
mode: ‘cors’ });

I have my app working now so my issue has been resolved.

Thanks for giving back to the community & posting your working code @VSingh! it’s extremely useful for anyone else with the same issue.

Sounds like it’s definitely worth me explicitly stating in the docs that the content-type should be “application/json” too, or potentially even updating the application to default to it if not passed.

Best, Aden

Hey!

I’m new to authentication and fetch and was wondering if someone would be able to tell me where I’ve gone wrong in my code, or provide a full working example. I’m following the above example, but when adding in my authentication key, I’m still getting 400 responses. I’m able to get responses and display them in my unauthenticated requests, so I think I’d messed up something with my headers. It seems to be failing at my getImages function :confused:

https://codepen.io/ethanol73/pen/mddqygR

Super appreciative if anyone can provide any help or context.

const url= "https://api.thecatapi.com/v1/images?limit=15";

//Set new headers
let h = new Headers();

//Send Request with authenticated API request 
let req = new Request(url, {
  method: "GET",
  headers: {
      "Content-Type": "application/json",
      "x-api-key": 'My_API_KEY' },
      mode: 'cors' });

// Function to get images, which is failing and returning 400 
function getImages(req) {
  fetch("https://api.thecatapi.com/v1/images")
  .then((res) => res.json())
  .then((data) => {
    console.log(data);
  }) 
}

getImages(req);