PagingRequest#getPagingParams JavaDoc and reorder RecordEntity#getName method.
CloudflareDNS-java
Preface
This project provides a java client for minimalistic access to the Cloudflare API version 4, which is mainly used for managing DNS settings such as creating, updating and deleting DNS records.
If you encounter any bugs or find missing features, feel free to report them on the GitLab Issues page.
Disclaimer
This guide comes without any warranty. Use at your own risk. The author is not responsible for potential data loss, hardware damage or keyboard mishaps!
Get It
The project has its own maven repository. It can be added to the pom.xml:
<repositories>
<repository>
<id>gitlab-cloudflare</id>
<url>https://gitlab.com/api/v4/projects/68509751/packages/maven</url>
</repository>
</repositories>
The dependency is:
<dependency>
<groupId>codes.thischwa</groupId>
<artifactId>cloudflaredns</artifactId>
<version>[version]</version>
</dependency>
Changelog
- 0.2.0-beta-SNAPSHOT:
- CfClient#sldInfo must return multiple RecordEntries
- add a missing source jar
- ResponseResultInfo#Errors: wrong object structure
- changing multiple records with put, post, patch and delete for dns-records
- 0.1.0:
- refactored / extended tests
- 0.1.0-beta.3:
- fixed json deserialization
- added logging of api errors
- 0.1.0-beta.1: 1st runnable version
Methods Overview
The methods can be categorized as follows:
Zone: list, infoRecord: list, info, create, update, delete
The following text focuses on the basic methods. For further information, take a look at the javadoc of the CfDnsClient.
Instantiation of CfDnsClient
CfDnsClient cfDnsClient = new CfDnsClient(
"email@example.com", "yourApiKey"
);
zoneListAll
Retrieve all zones within the Cloudflare account.
- Returns: A list of
ZoneEntityobjects.
List<ZoneEntity> zones = cfDnsClient.zoneListAll();
zones.forEach(zone -> System.out.println("Zone: " + zone.getName()));
zoneInfo
Get detailed information about a specific zone by its name.
- Parameters:
String name- The zone name (e.g., "example.com").
- Returns: A
ZoneEntityobject.
ZoneEntity zone = cfDnsClient.zoneInfo("example.com");
System.out.println("Zone ID: " + zone.getId());
sldListAll
Retrieve all records for a specific second-level domain (SLD) under a given zone.
- Parameters:
ZoneEntity zone- The zone object.String sld- Second-level domain (e.g., "www" in "www.example.com").
- Returns: A list of
RecordEntityobjects.
List<RecordEntity> records = cfDnsClient.sldListAll(zone, "sld");
records.forEach(record ->
System.out.println("Record Type: " + record.getType() + ", Value: " + record.getContent())
);
sldInfo
Retrieve DNS record details for a specific SLD and zone, optionally filtered by record types.
- Parameters:
ZoneEntity zone- The zone object.String sld- The second-level domain.RecordType... types- Optional record types to filter by (e.g., A, CNAME). If not specified, returns all record types.
- Returns: A list of
RecordEntityobjects matching the criteria.
// Get all records for a specific SLD
List<RecordEntity> allRecords = cfDnsClient.sldInfo(zone, "www");
allRecords.
forEach(record ->
System.out.
println("Type: "+record.getType() +", Content: "+record.
getContent())
);
// Get only A records
List<RecordEntity> aRecords = cfDnsClient.sldInfo(zone, "www", RecordType.A);
System.out.
println("Found "+aRecords.size() +" A records");
// Get A and AAAA records
List<RecordEntity> ipRecords = cfDnsClient.sldInfo(zone, "www", RecordType.A, RecordType.AAAA);
ipRecords.
forEach(record ->System.out.
println("IP Record: "+record.getContent()));
recordCreate
Create a new DNS record in a specific zone.
- Parameters:
ZoneEntity zone- DNS zone object.String sld- The sub-tld of the new record.int ttl- The time-to-live in seconds of the new rcord.
RecordEntity created = client.recordCreateSld(zone, "api", 60, RecordType.A, "192.168.1.1");
System.out.println("Created Record ID: " + created.getId());
recordUpdate
Update an existing DNS record.
- Parameters:
ZoneEntity zone- The zone that contains the record.RecordEntity rec- Updated record data.
record.setContent("192.168.1.2");
RecordEntity updated = cfDnsClient.recordUpdate(zone, record);
System.out.println("Updated Record: " + updated.getContent());
recordDelete
Delete a DNS record from a zone.
- Parameters:
ZoneEntity zone- The parent zone.RecordEntity rec- Record to delete.
boolean isDeleted = cfDnsClient.recordDelete(zone, record);
System.out.println(isDeleted ? "Deletion successful." : "Deletion failed.");
recordDeleteTypeIfExists
Delete a DNS record of a specific type if it exists.
- Parameters:
ZoneEntity zone- Target zone.String sld- Second-level domain.RecordType type- Record type.
cfDnsClient.recordDeleteTypeIfExists(zone, "api", RecordType.A);
System.out.println("Deletion attempt completed.");
Batch Operations
Process multiple DNS record operations (POST, PUT, PATCH, DELETE) in a single batch request.
- Parameters:
ZoneEntity zone- The target zone.List<RecordEntity> postRecords- Records to create (nullable).List<RecordEntity> putRecords- Records to fully replace (nullable).List<RecordEntity> patchRecords- Records to partially update (nullable).List<RecordEntity> deleteRecords- Records to delete (nullable).
- Returns: A
BatchEntryobject containing the processed records.
Batch Create (POST)
List<RecordEntity> newRecords = Arrays.asList(
RecordEntity.build("api." + zone.getName(), RecordType.A, 60, "192.168.1.10"),
RecordEntity.build("cdn." + zone.getName(), RecordType.A, 60, "192.168.1.11"),
RecordEntity.build("mail." + zone.getName(), RecordType.A, 60, "192.168.1.12")
);
BatchEntry result = cfDnsClient.recordBatch(zone, newRecords, null, null, null);
System.out.
println("Created "+result.getPosts().
size() +" records.");
Batch Update (PATCH)
// Fetch existing records and modify them
List<RecordEntity> recordsToUpdate = Arrays.asList(
cfDnsClient.sldInfo(zone, "api", RecordType.A),
cfDnsClient.sldInfo(zone, "cdn", RecordType.A)
);
recordsToUpdate.
forEach(record ->record.
setContent("192.168.2.10"));
BatchEntry result = cfDnsClient.recordBatch(zone, null, null, recordsToUpdate, null);
System.out.
println("Updated "+result.getPatches().
size() +" records.");
Batch Replace (PUT)
// Fetch existing records and fully replace them
List<RecordEntity> recordsToReplace = Arrays.asList(
cfDnsClient.sldInfo(zone, "api", RecordType.A),
cfDnsClient.sldInfo(zone, "cdn", RecordType.A)
);
recordsToReplace.
get(0).
setContent("192.168.3.10");
recordsToReplace.
get(0).
setTtl(120);
BatchEntry result = cfDnsClient.recordBatch(zone, null, recordsToReplace, null, null);
System.out.
println("Replaced "+result.getPuts().
size() +" records.");
Batch Delete
List<RecordEntity> recordsToDelete = Arrays.asList(
cfDnsClient.sldInfo(zone, "api", RecordType.A),
cfDnsClient.sldInfo(zone, "mail", RecordType.A)
);
BatchEntry result = cfDnsClient.recordBatch(zone, null, null, null, recordsToDelete);
System.out.
println("Deleted records.");
Combined Batch Operations
// You can combine multiple operations in a single batch request
BatchEntry result = cfDnsClient.recordBatch(
zone,
newRecords, // POST
putRecords, // PUT
patchRecords, // PATCH
deleteRecords // DELETE
);
Notes on Error Handling
The CfDnsClient provides internal error-handling mechanisms through exceptions. For example:
CloudflareApiExceptionis thrown for errors during API communication or invalid responses.CloudflareNotFoundExceptionis thrown when the requested single resource is not found, if enabled via theemptyResultThrowsExceptionflag during initialization.
Example:
try {
RecordEntity record = cfDnsClient.sldInfo(zone, "www", RecordType.A);
System.out.println("Record IP: " + record.getContent());
} catch (CloudflareApiException e) {
if (e instanceof CloudflareNotFoundException) {
log.warn("Sld not found: www");
} else {
log.error("Error while getting sld info of www", e);
throw e;
}
}
Summary
CfDnsClient offers a simple interface for managing DNS entries via Cloudflare's public API, allowing seamless CRUD
operations and automation-friendly workflows.