Searchmetrics Developers API

Examples

Java example

Note: in the example below we are using AsyncHttpClient to make HTTP requests, but this is not a requirement - you can use any library or plain Java instead.

Sample class to use with API

import org.asynchttpclient.AsyncHttpClient;
import org.asynchttpclient.Request;
import org.asynchttpclient.Response;

import static org.asynchttpclient.Dsl.asyncHttpClient;

public class SmApiGraphQLExample {
    private final String apiUrl = "https://graphql.searchmetrics.com/";
    private final String apiKey = "your_api_key";
    private final String apiSecret = "your_api_secret_key";
    private final AsyncHttpClient httpClientExample;

    public SmApiGraphQLExample() {
        httpClientExample = asyncHttpClient();
    }

    public Response getData(final String request) {

        final Request postRequest = httpClientExample.preparePost(apiUrl)
                .setBody(request)
                .setHeader("Content-Type", "application/json")
                .setHeader("sm-api-key", apiKey)
                .setHeader("sm-api-secret", apiSecret)
                .build();

        return executeRequestExample(postRequest);
    }

    private Response executeRequestExample(Request request) {
        Response response = null;

        try {
            response = httpClientExample.executeRequest(request).get();
        } catch (Exception e) {
            // catch errors or rethrow exception
        }

        if (null != response && response.getStatusCode() != 200) {
            // catch errors or throw exception
        }

        return response;
    }
}

Sample class usage

final SmApiGraphQLExample exampleObject = new SmApiGraphQLExample();

final String query = "{ \"query\": \"{ greeting { randomId who } }\" }";
exampleObject.getData(query).getResponseBody();
// {"data":{"greeting":{"randomId":"9404312","who":"Hello Name"}}}


final String mutation = "{\"query\": \"mutation { create_greeting(template: \\\"Hey\\\") { randomId who } }\" }";
exampleObject.getData(mutation).getResponseBody();
// {"data":{"create_greeting":{"randomId":"9193410","who":"Hey Name"}}}