Skip to content
This repository was archived by the owner on Jul 10, 2022. It is now read-only.

Creating a HTTP Request

Ian Castaño edited this page Aug 21, 2020 · 3 revisions

One of the biggest advantages of Centauri is that at no time is it directly responsible for making connections to the database, for this, a backend which has certain routes will do its job.

The HTTP requests API is based on the Google HTTP API, however, with some abstractions that allow much simpler use when executing requests.

Creating a callable

First of all, we need to create a RequestCallable. What is this? Simple, a small guide that the API needs to know what to do with the requested model and how to return it. For example: We need the method to return a User when executing an HTTP request, so in this case we will use a CoreRequestCallable, whose function is to obtain the response of the request and serialize it into a Java object.

TypeToken<User> typeToken = TypeToken.of(User.class);
RequestCallable<User> callable = new CoreRequestCallable<>(typeToken, mapper);

Providing options

You must provide the basic options so that the API knows what type of request to create, such as a request type (Eg: GET, POST, UDPATE, DELETE), headers a body and a query.

RequestOptions options = new CoreRequestOptions(Type.POST, new HashMap<>(), yourJSONBody, yourQueryString);

Executing a request

Once you have your options to execute the request, you must choose the route to which the request will be called and the type of object you expect to receive from it. Jackson's ObjectMapper will take care of serializing it for you.

Whenever you define a route, the initial configuration URL indicated in the HttpClientConfig will be used before it. (Eg: "https://perseus.astrocube.net/api/yourRoute").

public class MyHappyClass {
    
    private final @Inject HttpClient httpClient;

    public void myHappyQuery() {
        MyHappyModel model = this.httpClient.executeRequest(route, callable, options);
    }

}

Useful tip: To avoid making a specific class you can send an interface, Jackson's MrBean will use code generation to instantiate a specific class without necessarily using one created by you.

Clone this wiki locally