WordPress REST API Integration in Java: Complete Guide

The WordPress REST API provides programmatic access to WordPress content, users, and settings. Java applications can interact with it to create, read, update, and delete WordPress content.


1. WordPress REST API Overview

Key Endpoints

- Posts: /wp-json/wp/v2/posts
- Pages: /wp-json/wp/v2/pages  
- Users: /wp-json/wp/v2/users
- Media: /wp-json/wp/v2/media
- Comments: /wp-json/wp/v2/comments
- Categories: /wp-json/wp/v2/categories
- Tags: /wp-json/wp/v2/tags

Authentication Methods

  • Application Passwords (Recommended)
  • JWT Authentication
  • OAuth 1.0a
  • Basic Authentication (for development)

2. Project Setup and Dependencies

Maven Dependencies (pom.xml)

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>wordpress-api-client</artifactId>
<version>1.0.0</version>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<jackson.version>2.15.2</jackson.version>
<okhttp.version>4.11.0</okhttp.version>
<spring.boot.version>2.7.14</spring.boot.version>
</properties>
<dependencies>
<!-- HTTP Client -->
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>${okhttp.version}</version>
</dependency>
<!-- JSON Processing -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>${jackson.version}</version>
</dependency>
<!-- Spring Boot Starter Web (Optional) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>${spring.boot.version}</version>
</dependency>
<!-- Spring Boot Configuration Processor -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<version>${spring.boot.version}</version>
<optional>true</optional>
</dependency>
<!-- Logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>2.0.7</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring.boot.version}</version>
</plugin>
</plugins>
</build>
</project>

3. Configuration Classes

Application Properties (application.yml)

wordpress:
api:
base-url: https://your-wordpress-site.com
username: ${WORDPRESS_USERNAME:admin}
application-password: ${WORDPRESS_APP_PASSWORD:}
timeout: 30000
retry:
max-attempts: 3
backoff-delay: 1000
logging:
level:
com.example.wordpress: DEBUG

Configuration Properties Class

@Configuration
@ConfigurationProperties(prefix = "wordpress.api")
public class WordPressConfig {
private String baseUrl;
private String username;
private String applicationPassword;
private int timeout = 30000;
private RetryConfig retry = new RetryConfig();
// Getters and Setters
public String getBaseUrl() { return baseUrl; }
public void setBaseUrl(String baseUrl) { this.baseUrl = baseUrl; }
public String getUsername() { return username; }
public void setUsername(String username) { this.username = username; }
public String getApplicationPassword() { return applicationPassword; }
public void setApplicationPassword(String applicationPassword) { 
this.applicationPassword = applicationPassword; 
}
public int getTimeout() { return timeout; }
public void setTimeout(int timeout) { this.timeout = timeout; }
public RetryConfig getRetry() { return retry; }
public void setRetry(RetryConfig retry) { this.retry = retry; }
public static class RetryConfig {
private int maxAttempts = 3;
private long backoffDelay = 1000;
// Getters and Setters
public int getMaxAttempts() { return maxAttempts; }
public void setMaxAttempts(int maxAttempts) { this.maxAttempts = maxAttempts; }
public long getBackoffDelay() { return backoffDelay; }
public void setBackoffDelay(long backoffDelay) { this.backoffDelay = backoffDelay; }
}
}

4. Data Transfer Objects (DTOs)

Post DTO

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
@JsonIgnoreProperties(ignoreUnknown = true)
public class WordPressPost {
private Long id;
private String slug;
private String status;
private String type;
private String title;
private String content;
private String excerpt;
@JsonProperty("date_gmt")
@JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss")
private LocalDateTime date;
@JsonProperty("modified_gmt")
@JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss")
private LocalDateTime modified;
private List<Long> categories;
private List<Long> tags;
private Long author;
private String link;
private Map<String, Object> yoast; // Yoast SEO data
// Featured media
@JsonProperty("featured_media")
private Long featuredMedia;
// Getters and Setters
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getSlug() { return slug; }
public void setSlug(String slug) { this.slug = slug; }
public String getStatus() { return status; }
public void setStatus(String status) { this.status = status; }
public String getType() { return type; }
public void setType(String type) { this.type = type; }
public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; }
public String getContent() { return content; }
public void setContent(String content) { this.content = content; }
public String getExcerpt() { return excerpt; }
public void setExcerpt(String excerpt) { this.excerpt = excerpt; }
public LocalDateTime getDate() { return date; }
public void setDate(LocalDateTime date) { this.date = date; }
public LocalDateTime getModified() { return modified; }
public void setModified(LocalDateTime modified) { this.modified = modified; }
public List<Long> getCategories() { return categories; }
public void setCategories(List<Long> categories) { this.categories = categories; }
public List<Long> getTags() { return tags; }
public void setTags(List<Long> tags) { this.tags = tags; }
public Long getAuthor() { return author; }
public void setAuthor(Long author) { this.author = author; }
public String getLink() { return link; }
public void setLink(String link) { this.link = link; }
public Map<String, Object> getYoast() { return yoast; }
public void setYoast(Map<String, Object> yoast) { this.yoast = yoast; }
public Long getFeaturedMedia() { return featuredMedia; }
public void setFeaturedMedia(Long featuredMedia) { this.featuredMedia = featuredMedia; }
// Helper methods for title (can be string or object)
public void setTitle(Object title) {
if (title instanceof String) {
this.title = (String) title;
} else if (title instanceof Map) {
@SuppressWarnings("unchecked")
Map<String, String> titleMap = (Map<String, String>) title;
this.title = titleMap.get("rendered");
}
}
public void setContent(Object content) {
if (content instanceof String) {
this.content = (String) content;
} else if (content instanceof Map) {
@SuppressWarnings("unchecked")
Map<String, String> contentMap = (Map<String, String>) content;
this.content = contentMap.get("rendered");
}
}
}

Create/Update Post Request

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
@JsonInclude(JsonInclude.Include.NON_NULL)
public class CreatePostRequest {
private String title;
private String content;
private String excerpt;
private String status; // publish, draft, pending, private
private List<Long> categories;
private List<Long> tags;
private Long featuredMedia;
@JsonProperty("slug")
private String slug;
// Getters and Setters
public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; }
public String getContent() { return content; }
public void setContent(String content) { this.content = content; }
public String getExcerpt() { return excerpt; }
public void setExcerpt(String excerpt) { this.excerpt = excerpt; }
public String getStatus() { return status; }
public void setStatus(String status) { this.status = status; }
public List<Long> getCategories() { return categories; }
public void setCategories(List<Long> categories) { this.categories = categories; }
public List<Long> getTags() { return tags; }
public void setTags(List<Long> tags) { this.tags = tags; }
public Long getFeaturedMedia() { return featuredMedia; }
public void setFeaturedMedia(Long featuredMedia) { this.featuredMedia = featuredMedia; }
public String getSlug() { return slug; }
public void setSlug(String slug) { this.slug = slug; }
}

Media Upload Response

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.time.LocalDateTime;
import java.util.Map;
@JsonIgnoreProperties(ignoreUnknown = true)
public class WordPressMedia {
private Long id;
private String slug;
@JsonProperty("media_type")
private String mediaType;
@JsonProperty("mime_type")
private String mimeType;
@JsonProperty("source_url")
private String sourceUrl;
@JsonProperty("date_gmt")
private LocalDateTime date;
private String title;
private String description;
private String caption;
@JsonProperty("alt_text")
private String altText;
private Map<String, MediaSize> mediaDetails;
// Getters and Setters
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getSlug() { return slug; }
public void setSlug(String slug) { this.slug = slug; }
public String getMediaType() { return mediaType; }
public void setMediaType(String mediaType) { this.mediaType = mediaType; }
public String getMimeType() { return mimeType; }
public void setMimeType(String mimeType) { this.mimeType = mimeType; }
public String getSourceUrl() { return sourceUrl; }
public void setSourceUrl(String sourceUrl) { this.sourceUrl = sourceUrl; }
public LocalDateTime getDate() { return date; }
public void setDate(LocalDateTime date) { this.date = date; }
public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; }
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
public String getCaption() { return caption; }
public void setCaption(String caption) { this.caption = caption; }
public String getAltText() { return altText; }
public void setAltText(String altText) { this.altText = altText; }
public Map<String, MediaSize> getMediaDetails() { return mediaDetails; }
public void setMediaDetails(Map<String, MediaSize> mediaDetails) { this.mediaDetails = mediaDetails; }
@JsonIgnoreProperties(ignoreUnknown = true)
public static class MediaSize {
private String file;
private Integer width;
private Integer height;
@JsonProperty("mime_type") private String mimeType;
@JsonProperty("source_url") private String sourceUrl;
// Getters and Setters
public String getFile() { return file; }
public void setFile(String file) { this.file = file; }
public Integer getWidth() { return width; }
public void setWidth(Integer width) { this.width = width; }
public Integer getHeight() { return height; }
public void setHeight(Integer height) { this.height = height; }
public String getMimeType() { return mimeType; }
public void setMimeType(String mimeType) { this.mimeType = mimeType; }
public String getSourceUrl() { return sourceUrl; }
public void setSourceUrl(String sourceUrl) { this.sourceUrl = sourceUrl; }
}
}

5. WordPress REST API Client

Main API Client Service

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
@Service
public class WordPressApiClient {
private static final Logger logger = LoggerFactory.getLogger(WordPressApiClient.class);
private final WordPressConfig config;
private final OkHttpClient httpClient;
private final ObjectMapper objectMapper;
@Autowired
public WordPressApiClient(WordPressConfig config, ObjectMapper objectMapper) {
this.config = config;
this.objectMapper = objectMapper;
this.httpClient = new OkHttpClient.Builder()
.connectTimeout(config.getTimeout(), TimeUnit.MILLISECONDS)
.readTimeout(config.getTimeout(), TimeUnit.MILLISECONDS)
.writeTimeout(config.getTimeout(), TimeUnit.MILLISECONDS)
.addInterceptor(new AuthInterceptor(config.getUsername(), config.getApplicationPassword()))
.addInterceptor(new RetryInterceptor(config.getRetry().getMaxAttempts(), 
config.getRetry().getBackoffDelay()))
.build();
}
// Posts Operations
public List<WordPressPost> getPosts() throws WordPressApiException {
return getPosts(Collections.emptyMap());
}
public List<WordPressPost> getPosts(int page, int perPage) throws WordPressApiException {
return getPosts(Map.of(
"page", String.valueOf(page),
"per_page", String.valueOf(perPage)
));
}
public List<WordPressPost> getPostsByCategory(long categoryId) throws WordPressApiException {
return getPosts(Map.of("categories", String.valueOf(categoryId)));
}
private List<WordPressPost> getPosts(Map<String, String> queryParams) throws WordPressApiException {
try {
HttpUrl.Builder urlBuilder = HttpUrl.parse(config.getBaseUrl() + "/wp-json/wp/v2/posts").newBuilder();
queryParams.forEach(urlBuilder::addQueryParameter);
Request request = new Request.Builder()
.url(urlBuilder.build())
.get()
.build();
try (Response response = httpClient.newCall(request).execute()) {
if (!response.isSuccessful()) {
throw new WordPressApiException("Failed to get posts: " + response.code() + " - " + response.message());
}
String responseBody = response.body().string();
return objectMapper.readValue(responseBody, new TypeReference<List<WordPressPost>>() {});
}
} catch (IOException e) {
throw new WordPressApiException("Error fetching posts", e);
}
}
public WordPressPost getPost(long postId) throws WordPressApiException {
try {
Request request = new Request.Builder()
.url(config.getBaseUrl() + "/wp-json/wp/v2/posts/" + postId)
.get()
.build();
try (Response response = httpClient.newCall(request).execute()) {
if (!response.isSuccessful()) {
throw new WordPressApiException("Failed to get post: " + response.code() + " - " + response.message());
}
String responseBody = response.body().string();
return objectMapper.readValue(responseBody, WordPressPost.class);
}
} catch (IOException e) {
throw new WordPressApiException("Error fetching post: " + postId, e);
}
}
public WordPressPost createPost(CreatePostRequest postRequest) throws WordPressApiException {
try {
String jsonBody = objectMapper.writeValueAsString(postRequest);
RequestBody body = RequestBody.create(
jsonBody,
MediaType.parse("application/json")
);
Request request = new Request.Builder()
.url(config.getBaseUrl() + "/wp-json/wp/v2/posts")
.post(body)
.build();
try (Response response = httpClient.newCall(request).execute()) {
if (!response.isSuccessful()) {
String errorBody = response.body().string();
throw new WordPressApiException("Failed to create post: " + response.code() + " - " + response.message() + " - " + errorBody);
}
String responseBody = response.body().string();
return objectMapper.readValue(responseBody, WordPressPost.class);
}
} catch (IOException e) {
throw new WordPressApiException("Error creating post", e);
}
}
public WordPressPost updatePost(long postId, CreatePostRequest postRequest) throws WordPressApiException {
try {
String jsonBody = objectMapper.writeValueAsString(postRequest);
RequestBody body = RequestBody.create(
jsonBody,
MediaType.parse("application/json")
);
Request request = new Request.Builder()
.url(config.getBaseUrl() + "/wp-json/wp/v2/posts/" + postId)
.put(body)
.build();
try (Response response = httpClient.newCall(request).execute()) {
if (!response.isSuccessful()) {
String errorBody = response.body().string();
throw new WordPressApiException("Failed to update post: " + response.code() + " - " + response.message() + " - " + errorBody);
}
String responseBody = response.body().string();
return objectMapper.readValue(responseBody, WordPressPost.class);
}
} catch (IOException e) {
throw new WordPressApiException("Error updating post: " + postId, e);
}
}
public boolean deletePost(long postId) throws WordPressApiException {
try {
Request request = new Request.Builder()
.url(config.getBaseUrl() + "/wp-json/wp/v2/posts/" + postId)
.delete()
.build();
try (Response response = httpClient.newCall(request).execute()) {
if (!response.isSuccessful()) {
throw new WordPressApiException("Failed to delete post: " + response.code() + " - " + response.message());
}
return true;
}
} catch (IOException e) {
throw new WordPressApiException("Error deleting post: " + postId, e);
}
}
// Media Operations
public WordPressMedia uploadMedia(File file, String title, String altText) throws WordPressApiException {
try {
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", file.getName(),
RequestBody.create(file, MediaType.parse("application/octet-stream")))
.addFormDataPart("title", title)
.addFormDataPart("alt_text", altText)
.build();
Request request = new Request.Builder()
.url(config.getBaseUrl() + "/wp-json/wp/v2/media")
.post(requestBody)
.build();
try (Response response = httpClient.newCall(request).execute()) {
if (!response.isSuccessful()) {
String errorBody = response.body().string();
throw new WordPressApiException("Failed to upload media: " + response.code() + " - " + response.message() + " - " + errorBody);
}
String responseBody = response.body().string();
return objectMapper.readValue(responseBody, WordPressMedia.class);
}
} catch (IOException e) {
throw new WordPressApiException("Error uploading media", e);
}
}
// Categories Operations
public List<WordPressCategory> getCategories() throws WordPressApiException {
try {
Request request = new Request.Builder()
.url(config.getBaseUrl() + "/wp-json/wp/v2/categories")
.get()
.build();
try (Response response = httpClient.newCall(request).execute()) {
if (!response.isSuccessful()) {
throw new WordPressApiException("Failed to get categories: " + response.code() + " - " + response.message());
}
String responseBody = response.body().string();
return objectMapper.readValue(responseBody, new TypeReference<List<WordPressCategory>>() {});
}
} catch (IOException e) {
throw new WordPressApiException("Error fetching categories", e);
}
}
// Users Operations
public List<WordPressUser> getUsers() throws WordPressApiException {
try {
Request request = new Request.Builder()
.url(config.getBaseUrl() + "/wp-json/wp/v2/users")
.get()
.build();
try (Response response = httpClient.newCall(request).execute()) {
if (!response.isSuccessful()) {
throw new WordPressApiException("Failed to get users: " + response.code() + " - " + response.message());
}
String responseBody = response.body().string();
return objectMapper.readValue(responseBody, new TypeReference<List<WordPressUser>>() {});
}
} catch (IOException e) {
throw new WordPressApiException("Error fetching users", e);
}
}
}

Authentication Interceptor

import okhttp3.*;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import java.util.Base64;
public class AuthInterceptor implements Interceptor {
private final String credentials;
public AuthInterceptor(String username, String applicationPassword) {
String auth = username + ":" + applicationPassword;
this.credentials = "Basic " + Base64.getEncoder().encodeToString(auth.getBytes());
}
@NotNull
@Override
public Response intercept(@NotNull Chain chain) throws IOException {
Request originalRequest = chain.request();
Request authenticatedRequest = originalRequest.newBuilder()
.header("Authorization", credentials)
.header("User-Agent", "WordPress-Java-Client/1.0")
.build();
return chain.proceed(authenticatedRequest);
}
}

Retry Interceptor

import okhttp3.*;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
public class RetryInterceptor implements Interceptor {
private static final Logger logger = LoggerFactory.getLogger(RetryInterceptor.class);
private final int maxRetries;
private final long backoffDelay;
public RetryInterceptor(int maxRetries, long backoffDelay) {
this.maxRetries = maxRetries;
this.backoffDelay = backoffDelay;
}
@NotNull
@Override
public Response intercept(@NotNull Chain chain) throws IOException {
Request request = chain.request();
Response response = null;
IOException exception = null;
for (int attempt = 1; attempt <= maxRetries; attempt++) {
try {
response = chain.proceed(request);
if (response.isSuccessful()) {
return response;
}
// Only retry on server errors (5xx) or specific client errors
if (response.code() < 500 && response.code() != 429) {
return response;
}
logger.warn("Request failed with status {} on attempt {}/{}", 
response.code(), attempt, maxRetries);
} catch (IOException e) {
exception = e;
logger.warn("Request failed with IOException on attempt {}/{}: {}", 
attempt, maxRetries, e.getMessage());
}
if (attempt < maxRetries) {
try {
long delay = backoffDelay * (long) Math.pow(2, attempt - 1);
TimeUnit.MILLISECONDS.sleep(delay);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IOException("Request interrupted", e);
}
}
if (response != null) {
response.close();
}
}
if (exception != null) {
throw exception;
}
return response; // Return the last response if all retries failed
}
}

6. Additional DTOs

Category and User DTOs

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
@JsonIgnoreProperties(ignoreUnknown = true)
public class WordPressCategory {
private Long id;
private String name;
private String slug;
private String description;
@JsonProperty("parent")
private Long parentId;
private Integer count;
// Getters and Setters
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getSlug() { return slug; }
public void setSlug(String slug) { this.slug = slug; }
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
public Long getParentId() { return parentId; }
public void setParentId(Long parentId) { this.parentId = parentId; }
public Integer getCount() { return count; }
public void setCount(Integer count) { this.count = count; }
}
@JsonIgnoreProperties(ignoreUnknown = true)
public class WordPressUser {
private Long id;
private String name;
private String slug;
private String description;
@JsonProperty("avatar_urls")
private Map<String, String> avatarUrls;
// Getters and Setters
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getSlug() { return slug; }
public void setSlug(String slug) { this.slug = slug; }
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
public Map<String, String> getAvatarUrls() { return avatarUrls; }
public void setAvatarUrls(Map<String, String> avatarUrls) { this.avatarUrls = avatarUrls; }
}

7. Spring Boot Controller

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/wordpress")
public class WordPressController {
@Autowired
private WordPressApiClient wordPressClient;
@GetMapping("/posts")
public ResponseEntity<List<WordPressPost>> getPosts(
@RequestParam(defaultValue = "1") int page,
@RequestParam(defaultValue = "10") int perPage) {
try {
List<WordPressPost> posts = wordPressClient.getPosts(page, perPage);
return ResponseEntity.ok(posts);
} catch (WordPressApiException e) {
return ResponseEntity.status(500).body(null);
}
}
@GetMapping("/posts/{id}")
public ResponseEntity<WordPressPost> getPost(@PathVariable Long id) {
try {
WordPressPost post = wordPressClient.getPost(id);
return ResponseEntity.ok(post);
} catch (WordPressApiException e) {
return ResponseEntity.notFound().build();
}
}
@PostMapping("/posts")
public ResponseEntity<WordPressPost> createPost(@RequestBody CreatePostRequest postRequest) {
try {
WordPressPost post = wordPressClient.createPost(postRequest);
return ResponseEntity.ok(post);
} catch (WordPressApiException e) {
return ResponseEntity.badRequest().body(null);
}
}
@PutMapping("/posts/{id}")
public ResponseEntity<WordPressPost> updatePost(@PathVariable Long id, 
@RequestBody CreatePostRequest postRequest) {
try {
WordPressPost post = wordPressClient.updatePost(id, postRequest);
return ResponseEntity.ok(post);
} catch (WordPressApiException e) {
return ResponseEntity.badRequest().body(null);
}
}
@DeleteMapping("/posts/{id}")
public ResponseEntity<Void> deletePost(@PathVariable Long id) {
try {
wordPressClient.deletePost(id);
return ResponseEntity.ok().build();
} catch (WordPressApiException e) {
return ResponseEntity.notFound().build();
}
}
@GetMapping("/categories")
public ResponseEntity<List<WordPressCategory>> getCategories() {
try {
List<WordPressCategory> categories = wordPressClient.getCategories();
return ResponseEntity.ok(categories);
} catch (WordPressApiException e) {
return ResponseEntity.status(500).body(null);
}
}
}

8. Custom Exception

public class WordPressApiException extends Exception {
public WordPressApiException(String message) {
super(message);
}
public WordPressApiException(String message, Throwable cause) {
super(message, cause);
}
}

9. Usage Examples

Spring Boot Application

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
@SpringBootApplication
@EnableConfigurationProperties(WordPressConfig.class)
public class WordPressApiApplication {
public static void main(String[] args) {
SpringApplication.run(WordPressApiApplication.class, args);
}
}

Example Usage

@Service
public class BlogService {
@Autowired
private WordPressApiClient wordPressClient;
public void demonstrateUsage() {
try {
// Get all posts
List<WordPressPost> posts = wordPressClient.getPosts(1, 10);
// Create a new post
CreatePostRequest newPost = new CreatePostRequest();
newPost.setTitle("Hello from Java");
newPost.setContent("This post was created from a Java application!");
newPost.setStatus("draft");
newPost.setCategories(List.of(1L)); // Uncategorized category
WordPressPost createdPost = wordPressClient.createPost(newPost);
System.out.println("Created post with ID: " + createdPost.getId());
// Upload an image
File imageFile = new File("path/to/image.jpg");
WordPressMedia media = wordPressClient.uploadMedia(
imageFile, 
"Featured Image", 
"Description of the image"
);
// Update post with featured image
newPost.setFeaturedMedia(media.getId());
newPost.setStatus("publish");
wordPressClient.updatePost(createdPost.getId(), newPost);
} catch (WordPressApiException e) {
e.printStackTrace();
}
}
}

This comprehensive Java client for WordPress REST API provides complete functionality for interacting with WordPress content, including posts, media, categories, and users, with proper authentication, error handling, and retry mechanisms.

Leave a Reply

Your email address will not be published. Required fields are marked *


Macro Nepal Helper