Skip to content
RoboFlax | Robin edited this page Feb 21, 2018 · 8 revisions

User Guide

Trawling through Javadoc isn't always the most effective way to learn how to make best use of a library. Here, you can find pleasant and readable explanations of the most powerful features of this Cloudflare - API/Library.

Table of contents

Getting Started

First, create an entry-point to use this api.

String CF_EMAIL = "your_cloudflare_email@example.com";
String CF_API_KEY = "your_cloudflare_api_key";

CloudflareAccess cfAccess = new CloudflareAccess(CF_EMAIL, CF_API_KEY);

Where can I get my API-Key/Email? (My Profile)

Changing Thread-Pooling

By default the thread-pool, which will be used for the async requests in implemented services, is Executors.newFixedThreadPool( 30 ), but you can specify your own thread-pool.

ExecutorService threadPool = Executors.newFixedThreadPool(100);
cfAccess = new CloudflareAccess(CF_EMAIL, CF_API_KEY, threadPool);

Or use the default thread-pool and just change the maximum amount of parallel running threads.

cfAccess = new CloudflareAccess(CF_EMAIL, CF_API_KEY, 100);

Using Services

Because of cloudflare's extremely voluminous api all topics are splitted up into different services. This helps us by keeping the overview. That means that every service represents one topic. Also, you can implement your own services, which we will talk later about.

In this example we want to get our user details and change some properties of them afterwards. (See in Docs) For that, we can use the already implemented UserService which allows us to use asynchronicity.

UserService userService = cfAccess.userService();

CompletableFuture<UserDetails> detailsFuture = userService.getUserDetails();
try {
    UserDetails userDetails = detailsFuture.get();
    System.out.println(userDetails);
} catch ( InterruptedException e ) {
    e.printStackTrace();
} catch ( ExecutionException e ) {
    System.err.println( "Error while getting user details:" );
    e.getCause().printStackTrace();
}
Map<String, Object> newDetails = new HashMap<>(); 
newDetails.put( "first_name", "John" );
newDetails.put( "country", "EU" );

CompletableFuture<UserDetails> detailsFuture = userService.updateUserDetails(newDetails);
try {
    UserDetails newDetailsFuture = newDetailsFuture.get();
    System.out.println(newDetailsFuture);
} catch ( InterruptedException e ) {
    e.printStackTrace();
} catch ( ExecutionException e ) {
    System.err.println( "Error while getting new user details:" );
    e.getCause().printStackTrace();
}

Building custom Cloudflare requests

If there is no implemented service yet, that fits your needs, you can build your own cloudflare request. (Building custom Cloudflare requests will be needed when you implement your own services.)

First, we introduce you to "categories". A Category will relieve you of tiring work and save any confusion. For example http requests for getting zone details or updating organization invitation roles, are structured different. The first is a GET request, the second a PATCH request and both need different query strings and http-bodys.

To make the job easier, just find the right Category and build it according to Cloudflare's API documentation.

For example we want to update a dns record. As the documentation already reveals, we need the zone-identifier, the record-identifier and of cause the affected data in our request involved.

This is a step-by-step instruction:

new CloudflareRequest( Category.UPDATE_DNS_RECORD, cfAccess )

Then we add the zone id and the record id in the right ordered way, like in the docs, to the request. zones/:zone_identifier/dns_records/:identifier - first the zone id, then the record id

String zoneId = "zone_identifier_which_we_retrieved_before";
String recordId = "record_identifier_which_we_retrieved_before";

new CloudflareRequest( Category.UPDATE_DNS_RECORD, cloudflareAccess )
        .orderedIdentifiers( zoneId, recordId  )

Afterwards we add the affected data into the body of the request. The docs wants the body to look like this: {"type":"A","name":"just-an-example.com","content":"127.0.0.1","ttl":6000,"proxied":false}

new CloudflareRequest( Category.UPDATE_DNS_RECORD, cloudflareAccess )
        .orderedIdentifiers( zoneId, recordId  )
        .body( "type", "A" )
        .body( "name", "just-an-example.com" )
        .body( "content" , "127.0.0.1")
        .body( "ttl" , 6000)
        .body( "proxied", false )

At the end we want to send the request to the Cloudflare servers by adding .send(); and get the response.

HttpResponse<CloudflareResponse> response = 
new CloudflareRequest( Category.UPDATE_DNS_RECORD, cloudflareAccess )
    .orderedIdentifiers( zoneId, recordId  )
    .body( "type", "A" )
    .body( "name", "just-an-example.com" )
    .body( "content" , "127.0.0.1")
    .body( "ttl" , 6000)
    .body( "proxied", false )
    .send();

You can also use the .send(Consumer<HttpResponse<CloudflareResponse>>) method which might be more convenient in most situations.

new CloudflareRequest( Category.UPDATE_DNS_RECORD, cloudflareAccess )
    .orderedIdentifiers( zoneId, recordId  )
    .body( "type", "A" )
    .body( "name", "just-an-example.com" )
    .body( "content" , "127.0.0.1")
    .body( "ttl" , 6000)
    .body( "proxied", false )
    .send( response -> {
        CloudflareResponse body = response.getBody();
        if ( response.isSuccessful() )
            // root means the whole returned json object
            System.out.println(body.getRoot());
        } );

Creating custom Services

As already mentioned a service represents one topic of Cloudflare's api and provides all their functionalities of this section. By creating custom service classes there is really nothing special to know. All you need is the CloudflareAccess object and the CloudflareRequest class to create new requests.

This is an example of a service which should provide functionalities about "organizations".

public class OrganizationsService {
    
    CloudflareAccess cfAccess;
    
    public OrganizationsService ( CloudflareAccess cfAccess ) {
        this.cfAccess = cfAccess;
    }
    
    public AN_OBJECT getAN_OBJECT( ) {
        new CloudflareRequest( Category.GET_AN_OBJECT, cfAccess )
            .send( response -> {
                if(response.isSuccessful())
                    return cfAccess.gson.fromJson( response.getBody().getAsObject(), AN_OBJECT.class );
            });
        return null;
    }

    // more methods...
}

Extending Service class

You can extend the abstract Service class to group your class as a service. It also contains the basics which should contain a service.

As an example for extending the Service class and provide an asynchronous runnable method to get something. Also we have some use of the ClouflareUtils class.

public class OrganizationsService extends Service implements MAYBE_YOUR_INTERFACE {
    
    public OrganizationsService ( CloudflareAccess cloudflareAccess ) {
        super( cloudflareAccess );
    }
    
    @Override
    public CompletableFuture<XXXXX> getXXXXX( ) {
        CompletableFuture<XXXXX> future = new CompletableFuture<>();
        cloudflareAccess.getThreadPool().submit( ( ) -> {
            HttpResponse<CloudflareResponse> http = new CloudflareRequest( Category.XXXXX, cloudflareAccess ).send();
            if ( ClouflareUtils.isValidHttpResponse( http, future ) )
                future.complete( gson.fromJson( http.getBody().getAsXXXXX(), XXXXX.class ) );
        } );
        return future;
    }

    // more methods...
}

This is it, for now. :) Feel free to ask me something or request more information about a feature.

Clone this wiki locally