A response is not just a status code. It also carries a body, and the body has a
shape. Sometimes the shape is a JSON object, which turns into a Map. Sometimes the
whole body is a JSON array, which turns into a List, and every item inside that
list is an object of its own. Read the shape before you read a value, or the
value you want will not be there.
The endpoint for a single product answers with a JSON object, so the body
becomes a Map with keys such as title, brand and category.
Map<String, Object> product = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
String title = (String) product.get('title');
The endpoint for the product categories answers with a JSON array instead: a
list of objects, and every one of them holds a slug and a name.
List<Object> rows = (List<Object>) JSON.deserializeUntyped(response.getBody());
for (Object item : rows) {
Map<String, Object> row = (Map<String, Object>) item;
String slug = (String) row.get('slug');
}
The cast is what tells you which shape you received. An array cast to a Map
fails the moment you use it, with System.TypeException: Invalid conversion from runtime type List<ANY> to Map<String,ANY>, so the shape is not a detail you
can guess later.
When the body is a list, you usually want one item out of it and not the whole
list. Walk the list, compare the key you care about with the value you were
given, and read the answer out of the item that matched.
for (Object item : rows) {
Map<String, Object> row = (Map<String, Object>) item;
if (slug == (String) row.get('slug')) {
return (String) row.get('name');
}
}
Apex compares strings without caring about case, so beauty and Beauty match
each other.
A list does not have to hold what you asked for. When no item matches, return
a value the caller can use, such as the text not found. Returning null leaves
the caller to guess what happened, and reading rows[0] on an empty list throws
List index out of bounds.
An error response has a body too, and that body is not the data you asked for.
Read the status code before you parse anything, and only parse the body of a
response that succeeded.
The first mistake is casting the body to the wrong shape, which throws as soon
as the value is used. The second is taking the first item of the list instead
of searching for the one you wanted. The third is returning null when nothing
matched, which hides the difference between an empty answer and a broken one.