+ Start a Discussion
Gonzalo Di GesuGonzalo Di Gesu 

SWAPI - HTTP Request - Error 301

Hello. I've been trying, for a few days now, to make an Apex HTTPRequest to the Star Wars API but keep getting error 301.
I looked everywhere for a solution but can't find one.

My class declaration is the following

@AuraEnabled
    public static Object getContactData(integer id){
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint('https://swapi.dev/api/people/' + id);
        request.setMethod('GET');
        HttpResponse response = http.send(request);
        List<Object> contact = new List<Object>();
    // If the request is successful, parse the JSON response.
    if (response.getStatusCode() == 200) {
    // Deserialize 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 'animals' key as a list
     Map<String, Object> person = (Map<String, Object>)results.get('namel');
     contact.add(person);
    }
        return contact;
    }

Keep getting an empty Array. And if I use the debug console, I get the 301 error. I tried a similar code with the heroku animal API and it worked.

Thanks and sorry for the inconvenience, I'm new to Apex
Best Answer chosen by Gonzalo Di Gesu
VinayVinay (Salesforce Developers) 
Can you check if endpoint should be something like below
http swapi.dev/api/planets/1/
https://swapi.dev/documentation

Thanks,

All Answers

VinayVinay (Salesforce Developers) 
Hi Gonzalo,

A status code of 301 tells a client that the resource they asked for has permanently moved to a new location. The response should also include this location. It tells the client to use the new URL the next time it wants to fetch the same resource.

Try to use API testing tools (SOAP UI, Postman) to check if you are getting a response when you hit endpoint URL.

Thanks,
Gonzalo Di GesuGonzalo Di Gesu
Thanks.
I tested it and it seems OK

HTTP/1.1 200 OK Server=nginx/1.16.1 Date=Sat, 21 Nov 2020 17:58:00 GMT Content-Type=application/json Transfer-Encoding=chunked Connection=keep-alive Vary=Accept, Cookie X-Frame-Options=SAMEORIGIN ETag="35e90fa80df5a1200859818a74a65a4e" Allow=GET, HEAD, OPTIONS Strict-Transport-Security=max-age=15768000

Also, I did a fetch in JavaScript and it worked perfectly. I don't know if I'm missing something in Apex but I'm not finding it.
VinayVinay (Salesforce Developers) 
Can you check if endpoint should be something like below
http swapi.dev/api/planets/1/
https://swapi.dev/documentation

Thanks,
This was selected as the best answer
Gonzalo Di GesuGonzalo Di Gesu
Yes, I was missing the '/' at the end. It seems the call wasn't redirecting to that url.  Thanks!