Consuming an API: means creating a client which can send requests to the API that you build.
We can use GET
on our web API https://javarestfulapi.herokuapp.com/todos
to fetch all our todos to be used in our application. It can be an application in any other programming language.
In this Lab we'll try to consume the web api we've created using applications in 3 different languages.
There are many ways to do this in java, but I'll be working with RestTemplateBuilder class provided by spring boot web.
import com.restful.RestfulApi.model.Todo;
import org.springframework.boot.web.client.RestTemplateBuilder;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
public class RestfulApiApplication {
private static RestTemplateBuilder builder = new RestTemplateBuilder();
public static void main(String[] args) {
Optional<List<Todo>> fectchedTodos = getTodosFromAPI();
if( fectchedTodos.isPresent()){
fectchedTodos.get().forEach(
todo -> System.out.println( "ID -> " + todo.getId() + "\t\tMessage -> " + todo.getMessage())
);
}else {
System.out.println("Empty Todo");
}
}
public static Optional<List<Todo>> getTodosFromAPI(){
Todo[] todos = builder.build().getForObject("https://javarestfulapi.herokuapp.com/todos", Todo[].class);
if ( todos == null){
return Optional.empty();
}
return Optional.of(Arrays.asList(todos));
}
}
Running this, it will fetch all the todos and print them out.
Same can be done using the requests librarry which is provided by default using python3, so there is no need for an pip install.
import requests
res = requests.get('https://javarestfulapi.herokuapp.com/todos')
print(res.json())
Running this piece of code also yield the same result.
Right click anywhere on your browser and click on inspect then console.
You can now Copy & Paste this piece of code to run it.
fetch('https://javarestfulapi.herokuapp.com/todos')
.then((response) => { return response.json(); })
.then((data) => { console.log(data); });
Running it for the first time we get an error due to CORS.
To fix it we'll need to add single annotation to a web server. add @CrossOrigin(origins = "*")
to our rest contoller.
Now push your code to GitHub and re-deploy the app.