[SalesForce] Create an Apex class that calls a REST endpoint and write a test class

In the challenge, it is specified :

The Apex class must be called 'AnimalLocator', have a 'getAnimalNameById' method that accepts an Integer and returns a String.

and i cannot understand the line :

public class AnimalLocator {
    public static String getAnimalNameById(Integer id){
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals/'+ id);
        request.setMethod('GET');
        HttpResponse response = http.send(request);
        if (response.getStatusCode() == 200) {
            Map<String, Object> results = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
            System.debug(results);
            if(results.size() > 0){
                for (Object animal : results.values()) {
                    System.debug(animal);
                }
            }
        }
        return String.valueOf(response) ;
    }    
}

As the debug result, i get ->

DEBUG|{"animals": ["majestic badger",
"fluffy bunny", "scary bear", "chicken", "mighty moose"]}

The expected result must be ->

{"animal":{"id":1,"name":"chicken","eats":"chicken food","says":"cluck
cluck"}}

i am unable to understand the issue!

Best Answer

There is no problem in your method. It is working fine.

As @Martin & @Keith mentioned in the comments, you must check for Id is not null. and make sure you are passing Integer as param to this method while calling it.

    public static String getAnimalNameById( Integer id ){
        if( id != null ){
            Http http = new Http();
            HttpRequest request = new HttpRequest();
            request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals/'+id);
            request.setMethod('GET');
            HttpResponse response = http.send(request);
            // If the request is successful, parse the JSON response.
            if (response.getStatusCode() == 200) {
                // Deserializes the JSON string into collections of primitive data types.
                Map<String, Object> results = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
                // Cast the values in the 'animal' key as a object
                Object animal = (Object) results.get('animal');
                System.debug('Received the following animal:');
                Map<String, Object> details = ( Map<String, Object> ) animal;
                String name = String.valueOf( details.get('name') );
                return name;
            }
        }
        return '';
    }

and call it as:

System.debug( '----> '+AnimalLocator.getAnimalNameById(1) );

It will get you the animal name as "chicken".

USER_DEBUG|[113]|DEBUG|----> chicken
Related Topic