### Get Sitemap (Java) Source: https://github.com/buttercms/buttercms-java/blob/master/README.md This example demonstrates retrieving the sitemap using the getSiteMap() method. The method returns an XmlDocument representing the sitemap. ```java XmlDocument siteMap = butterClient.getSiteMap(); ``` -------------------------------- ### Maven Installation for ButterCMS Java Client Source: https://github.com/buttercms/buttercms-java/blob/master/README.md This snippet shows how to add the ButterCMS Java client dependency to your project using Maven. Ensure you replace '1.13.0' with the latest version. ```xml ... com.buttercms buttercmsclient 1.13.0 ... ``` -------------------------------- ### Gradle Installation for ButterCMS Java Client Source: https://github.com/buttercms/buttercms-java/blob/master/README.md This snippet demonstrates how to include the ButterCMS Java client in your project's dependencies using Gradle. Always use the most recent version number available. ```gradle dependencies { implementation 'com.buttercms:buttercmsclient:1.13.0' } ``` -------------------------------- ### Initialize ButterCMSClient with Custom HttpClient Source: https://github.com/buttercms/buttercms-java/blob/master/README.md This example shows how to create a ButterCMSClient instance with a custom Apache HttpComponents HttpClient. This allows for advanced configurations like adding interceptors or default headers. ```java import com.buttercms.IButterCMSClient; import com.buttercms.ButterCMSClient; import org.apache.http.client.HttpClient; ... HttpClient you_http_client = HttpClients.custom() .addInterceptorFirst(you_interceptor) .setDefaultHeaders(you_headers) .build() IButterCMSClient client = new ButterCMSClient("your_api_token", isPreviewEnabled, you_http_client); ``` -------------------------------- ### Get Categories with Query Parameters (Java) Source: https://github.com/buttercms/buttercms-java/blob/master/README.md This example shows how to retrieve categories using the getCategories() method and passing query parameters. Query parameters can be used to control the data included in the response. ```java Map queryParams = new HashMap(){{ put("include","recent_posts"); ... }} CategoriesResponse getCategories = butterClient.getCategories(queryParams); ``` -------------------------------- ### Get Category by Slug with Query Parameters (Java) Source: https://github.com/buttercms/buttercms-java/blob/master/README.md This example demonstrates retrieving a specific category by its slug, using query parameters to customize the response data. The `queryParams` map allows for fine-grained control over the returned data. ```java Map queryParams = new HashMap(){{ put("include","recent_posts"); ... }} CategoryResponse getCategories = butterClient.getCategory("java",queryParams); ``` -------------------------------- ### Get Tags with Query Parameters (Java) Source: https://github.com/buttercms/buttercms-java/blob/master/README.md Illustrates retrieving a list of tags using the getTags() method and query parameters. Query parameters provide control over the response content. ```java Map queryParams = new HashMap(){{ put("include","recent_posts"); ... }} TagsResponse getTags = butterClient.getTags(queryParams); ``` -------------------------------- ### Get RSS Feed (Java) Source: https://github.com/buttercms/buttercms-java/blob/master/README.md This example demonstrates how to retrieve the RSS feed using the getRSS() method. The method returns a Document object representing the generated RSS feed. ```java Document rssFeed = butterClient.getRSS(); ``` -------------------------------- ### Get Authors with Query Parameters (Java) Source: https://github.com/buttercms/buttercms-java/blob/master/README.md This example demonstrates how to retrieve authors from ButterCMS using the getAuthors() method and passing query parameters. The query parameters are used to specify additional data to be included in the response. ```java Map queryParams = new HashMap(){{ put("include","recent_posts"); ... }} AuthorsResponse authors = butterClient.getAuthors(queryParams); ``` -------------------------------- ### Retrieve Atom Feed using ButterCMS Java SDK Source: https://context7.com/buttercms/buttercms-java/llms.txt Fetches the blog's Atom feed as an XML Document using the ButterCMS Java SDK. The example shows how to save the feed directly to an XML file. Requires the ButterCMS client object. ```java import org.w3c.dom.Document; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import java.io.File; try { Document atomFeed = client.getAtom(); // Write Atom feed to file TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.transform( new DOMSource(atomFeed), new StreamResult(new File("atom.xml")) ); System.out.println("Atom feed saved to atom.xml"); } catch (Exception e) { System.err.println("Error fetching Atom feed: " + e.getMessage()); } ``` -------------------------------- ### Get Tag by Slug with Query Parameters (Java) Source: https://github.com/buttercms/buttercms-java/blob/master/README.md Shows how to retrieve a specific tag by its slug using query parameters, allowing customization of the returned response. ```java Map queryParams = new HashMap(){{ put("include","recent_posts"); ... }} TagResponse getTag = butterClient.getTag("java",queryParams); ``` -------------------------------- ### Get Atom Feed (Java) Source: https://github.com/buttercms/buttercms-java/blob/master/README.md This example retrieves the Atom feed using the getAtom() method. The method returns a Document object representing the Atom feed. ```java Document atomFeed = butterClient.getAtom(); ``` -------------------------------- ### Get a Single Post by Slug Source: https://github.com/buttercms/buttercms-java/blob/master/README.md Retrieves a specific blog post using its unique slug. The response contains the post details and metadata, including information about the previous and next posts in the sequence. ```java PostResponse controversialPost = butterClient.getPost("tabs-vs-spaces-throwdown"); ``` -------------------------------- ### Get Author by Slug with Query Parameters (Java) Source: https://github.com/buttercms/buttercms-java/blob/master/README.md Demonstrates how to retrieve a single author by slug using the getAuthor() method and query parameters. The query parameters allow for customization of the response data. ```java Map queryParams = new HashMap(){{ put("include","recent_posts"); ... }} AuthorResponse authors = butterClient.getAuthor("john",queryParams); ``` -------------------------------- ### Get Posts with Query Parameters Source: https://github.com/buttercms/buttercms-java/blob/master/README.md Fetches a list of posts from ButterCMS, allowing for filtering and pagination via query parameters. The response includes pagination metadata and a list of posts. The 'exclude_body' parameter can reduce response size. ```java Map queryParams = new HashMap(){ put("exclude_body","true"); ... }; PostsResponse posts = butterClient.getPosts(queryParams); ``` -------------------------------- ### Get ButterCMS Collection Data in Java Source: https://github.com/buttercms/buttercms-java/blob/master/README.md Retrieves collection data from ButterCMS with specified query parameters. Allows filtering, sorting, pagination, and locale selection. It deserializes the response into a specified Java class. ```java CollectionResponse response = client.getCollection("cars", new HashMap() {{ put("fields.weight", "400"); put("page_size", "1"); }}, Car.class); ``` -------------------------------- ### Retrieve Single Category in Java Source: https://context7.com/buttercms/buttercms-java/llms.txt Get a specific category with optional inclusion of recent posts in that category. Uses category slug as input parameter. Displays category details along with associated posts when included. ```java import com.buttercms.model.CategoryResponse; import com.buttercms.model.Category; import java.util.HashMap; import java.util.Map; Map params = new HashMap() {{ put("include", "recent_posts"); }}; try { CategoryResponse categoryResponse = client.getCategory("tutorials", params); Category category = categoryResponse.getData(); System.out.println("Category: " + category.getName()); System.out.println("Slug: " + category.getSlug()); if (category.getRecentPosts() != null) { System.out.println("\nRecent posts in this category:"); category.getRecentPosts().forEach(post -> { System.out.println(" - " + post.getTitle()); }); } } catch (ButterCMSResponseException e) { System.err.println("Error fetching category: " + e.getMessage()); } ``` -------------------------------- ### Initialize ButterCMSClient with API Key Source: https://github.com/buttercms/buttercms-java/blob/master/README.md Instantiate the ButterCMSClient using your API token and a boolean indicating if preview mode should be enabled. Preview mode fetches draft content. The default timeout is 10 seconds. ```java import com.buttercms.IButterCMSClient; import com.buttercms.ButterCMSClient; ... IButterCMSClient client = new ButterCMSClient("your_api_token", isPreviewEnabled); ``` -------------------------------- ### Initialize ButterCMS Java Client Source: https://context7.com/buttercms/buttercms-java/llms.txt Demonstrates how to initialize the ButterCMS client with an API token. Supports enabling or disabling preview mode for accessing draft content. ```java import com.buttercms.IButterCMSClient; import com.buttercms.ButterCMSClient; // Initialize with preview mode disabled (production) IButterCMSClient client = new ButterCMSClient("your_api_token", false); // Initialize with preview mode enabled (to see draft content) IButterCMSClient client = new ButterCMSClient("your_api_token", true); ``` -------------------------------- ### List and Search Pages with Filtering - Java Source: https://context7.com/buttercms/buttercms-java/llms.txt Demonstrates Pages API operations including listing pages with filtering, sorting, and pagination, plus searching pages by keyword. Includes custom field filtering, relationship depth control, draft preview support, and pagination metadata handling. Requires ButterCMS client initialization and page type slug configuration. ```java import com.buttercms.model.PagesResponse; import com.buttercms.model.Page; import com.example.model.RecipePage; import java.util.HashMap; import java.util.Map; Map params = new HashMap() {{ put("page", "1"); put("page_size", "10"); put("locale", "en"); put("levels", "2"); // Depth of relationships to include put("fields.prep_time", "30"); // Filter by custom field put("order", "-cook_time"); // Sort by cook_time descending }}; try { PagesResponse pagesResponse = client.getPages( "recipe", // page type slug params, RecipePage.class ); for (Page page : pagesResponse.getData()) { RecipePage recipe = page.getFields(); System.out.println(recipe.getRecipeName() + " (Slug: " + page.getSlug() + ")"); System.out.println(" Total Time: " + (recipe.getPrepTime() + recipe.getCookTime()) + " min"); } // Handle pagination PaginationMeta meta = pagesResponse.getMeta(); System.out.println("\nTotal pages: " + meta.getCount()); System.out.println("Next page: " + meta.getNextPage()); } catch (ButterCMSResponseException e) { System.err.println("Error fetching pages: " + e.getMessage()); } ``` ```java import com.buttercms.model.PagesResponse; import com.buttercms.model.Page; import com.example.model.RecipePage; import java.util.HashMap; import java.util.Map; Map searchParams = new HashMap() {{ put("query", "chocolate dessert"); put("page", "1"); put("page_size", "10"); put("locale", "en"); put("preview", "1"); // Include draft pages }}; try { PagesResponse searchResults = client.getSearchPages( "recipe", searchParams, RecipePage.class ); System.out.println("Found " + searchResults.getMeta().getCount() + " recipes"); for (Page page : searchResults.getData()) { RecipePage recipe = page.getFields(); System.out.println(recipe.getRecipeName()); System.out.println(" Status: " + page.getStatus()); } } catch (ButterCMSResponseException e) { System.err.println("Search error: " + e.getMessage()); } ``` -------------------------------- ### Retrieve Sitemap using ButterCMS Java SDK Source: https://context7.com/buttercms/buttercms-java/llms.txt Fetches the blog's sitemap as an XML Document using the ButterCMS Java SDK. This snippet demonstrates parsing the sitemap to extract URLs and also saving the entire sitemap to an XML file. Requires the ButterCMS client object. ```java import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.w3c.dom.Element; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import java.io.File; try { Document sitemap = client.getSiteMap(); // Parse sitemap URLs NodeList urlElements = sitemap.getElementsByTagName("url"); System.out.println("Sitemap contains " + urlElements.getLength() + " URLs"); for (int i = 0; i < urlElements.getLength(); i++) { Element urlElement = (Element) urlElements.item(i); String loc = urlElement.getElementsByTagName("loc").item(0).getTextContent(); System.out.println(" " + loc); } // Save to file TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.transform( new DOMSource(sitemap), new StreamResult(new File("sitemap.xml")) ); } catch (Exception e) { System.err.println("Error fetching sitemap: " + e.getMessage()); } ``` -------------------------------- ### Retrieve Single Blog Post using ButterCMS Java SDK Source: https://context7.com/buttercms/buttercms-java/llms.txt Fetches a single blog post by its slug using the ButterCMS Java SDK. It retrieves full content, metadata, author details, categories, and tags. Includes basic error handling for API responses. ```java import com.buttercms.model.PostResponse; import com.buttercms.model.Post; import com.buttercms.exception.ButterCMSResponseException; try { // Get a single post by slug PostResponse postResponse = client.getPost("my-first-blog-post"); Post post = postResponse.getData(); // Access post properties System.out.println("Title: " + post.getTitle()); System.out.println("Body: " + post.getBody()); System.out.println("Author: " + post.getAuthor().getFirstName() + " " + post.getAuthor().getLastName()); System.out.println("Published: " + post.getPublished()); System.out.println("URL: " + post.getUrl()); System.out.println("Featured Image: " + post.getFeaturedImage()); System.out.println("SEO Title: " + post.getSeoTitle()); System.out.println("Meta Description: " + post.getMetaDescription()); } catch (ButterCMSResponseException e) { System.err.println("Error fetching post: " + e.getMessage()); } ``` -------------------------------- ### Search Posts by Keyword in Java Source: https://context7.com/buttercms/buttercms-java/llms.txt Search blog posts by keyword across title, body, and summary fields. Requires a ButterCMS client instance and handles pagination through parameters. Outputs count of results and post titles with summaries. ```java import com.buttercms.model.PostsResponse; import java.util.HashMap; import java.util.Map; Map searchParams = new HashMap() {{ put("query", "java spring boot"); put("page", "1"); put("page_size", "20"); }}; try { PostsResponse searchResults = client.getSearchPosts(searchParams); System.out.println("Found " + searchResults.getMeta().getCount() + " posts"); searchResults.getData().forEach(post -> { System.out.println(post.getTitle()); System.out.println(" " + post.getSummary()); }); } catch (ButterCMSResponseException e) { System.err.println("Search error: " + e.getMessage()); } ``` -------------------------------- ### Initialize ButterCMS Java Client with Custom HTTP Client Source: https://context7.com/buttercms/buttercms-java/llms.txt Shows how to configure a custom Apache HttpClient for the ButterCMS client, allowing settings like connection timeouts and custom interceptors. This is useful for advanced network configurations. ```java import com.buttercms.IButterCMSClient; import com.buttercms.ButterCMSClient; import org.apache.http.client.HttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.client.config.RequestConfig; // Create custom HTTP client with 30-second timeout RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(30000) .setSocketTimeout(30000) .build(); HttpClient customHttpClient = HttpClients.custom() .setDefaultRequestConfig(requestConfig) .build(); // Initialize client with custom HTTP client IButterCMSClient client = new ButterCMSClient("your_api_token", false, customHttpClient); ``` -------------------------------- ### List Blog Posts with Filters using ButterCMS Java SDK Source: https://context7.com/buttercms/buttercms-java/llms.txt Retrieves a list of blog posts with options for pagination, filtering by author or category slug, and excluding the post body. It also demonstrates how to access pagination metadata. ```java import com.buttercms.model.PostsResponse; import com.buttercms.model.Post; import com.buttercms.model.PaginationMeta; import java.util.HashMap; import java.util.Map; import java.util.List; // Build query parameters Map queryParams = new HashMap() {{ put("page", "1"); put("page_size", "10"); put("exclude_body", "true"); // Exclude post body for list views put("category_slug", "java-tutorials"); put("author_slug", "john-doe"); }}; try { PostsResponse postsResponse = client.getPosts(queryParams); List posts = postsResponse.getData(); PaginationMeta meta = postsResponse.getMeta(); // Display posts for (Post post : posts) { System.out.println(post.getTitle() + " - " + post.getSummary()); } // Handle pagination System.out.println("Total count: " + meta.getCount()); System.out.println("Next page: " + meta.getNextPage()); System.out.println("Previous page: " + meta.getPreviousPage()); } catch (ButterCMSResponseException e) { System.err.println("Error fetching posts: " + e.getMessage()); } ``` -------------------------------- ### Retrieve RSS Feed using ButterCMS Java SDK Source: https://context7.com/buttercms/buttercms-java/llms.txt Fetches the blog's RSS feed as an XML Document using the ButterCMS Java SDK. It demonstrates converting the Document to a string and provides an option to save it to a file. Requires the ButterCMS client object. ```java import org.w3c.dom.Document; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import java.io.StringWriter; try { Document rssFeed = client.getRSS(); // Convert XML Document to string TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(rssFeed), new StreamResult(writer)); String rssXml = writer.toString(); System.out.println(rssXml); // Or write to file // transformer.transform(new DOMSource(rssFeed), new StreamResult(new File("rss.xml"))); } catch (Exception e) { System.err.println("Error fetching RSS feed: " + e.getMessage()); } ``` -------------------------------- ### List All Tags Using ButterCMS Java Client Source: https://context7.com/buttercms/buttercms-java/llms.txt This code retrieves all blog tags with optional inclusion of recent posts per tag via ButterCMS Java client. It depends on the client and TagsResponse model, iterating over tags to print names, slugs, and post counts. Inputs are parameters like 'include=recent_posts'; outputs list of tags with post info; errors caught via ButterCMSResponseException. ```java import com.buttercms.model.TagsResponse; import com.buttercms.model.Tag; import java.util.HashMap; import java.util.Map; Map params = new HashMap() {{ put("include", "recent_posts"); }}; try { TagsResponse tagsResponse = client.getTags(params); for (Tag tag : tagsResponse.getData()) { System.out.println(tag.getName() + " (" + tag.getSlug() + ")"); if (tag.getRecentPosts() != null) { System.out.println(" Posts: " + tag.getRecentPosts().size()); } } } catch (ButterCMSResponseException e) { System.err.println("Error fetching tags: " + e.getMessage()); } ``` -------------------------------- ### Search Posts with Query Source: https://github.com/buttercms/buttercms-java/blob/master/README.md Performs a search across blog posts using a specified query string. This method returns a paginated response containing matching posts. You can also specify page number and size. ```java Map queryParams = new HashMap(){ put("query", "search query"); ... }; PostsResponse posts = butterClient.getSearchPosts(queryParams); ``` -------------------------------- ### Feeds API Source: https://github.com/buttercms/buttercms-java/blob/master/README.md Endpoints for generating blog feeds in various formats. ```APIDOC ## GET /feeds/rss ### Description Retrieves a fully generated RSS feed for your blog. ### Method GET ### Endpoint /feeds/rss ### Response #### Success Response (200) - **Document** - An XML Document object representing the RSS feed. ### Request Example ```java Document rssFeed = butterClient.getRSS(); ``` ## GET /feeds/atom ### Description Retrieves a fully generated Atom feed for your blog. ### Method GET ### Endpoint /feeds/atom ### Response #### Success Response (200) - **Document** - An XML Document object representing the Atom feed. ### Request Example ```java Document atomFeed = butterClient.getAtom(); ``` ## GET /sitemap.xml ### Description Retrieves a fully generated sitemap for your blog. ### Method GET ### Endpoint /sitemap.xml ### Response #### Success Response (200) - **XmlDocument** - An XML Document object representing the sitemap. ### Request Example ```java XmlDocument siteMap = butterClient.getSiteMap(); ``` ``` -------------------------------- ### Retrieve Single Page Using ButterCMS Java Client Source: https://context7.com/buttercms/buttercms-java/llms.txt This snippet fetches a custom page by type and slug using ButterCMS Java client, deserializing fields into a provided model class like RecipePage. It supports parameters such as locale and handles exceptions; outputs include page fields (e.g., recipe details) and metadata like slug/status. Dependencies: client, PageResponse, and custom model. ```java import com.buttercms.model.PageResponse; import com.buttercms.model.Page; import com.example.model.RecipePage; import java.util.HashMap; import java.util.Map; Map params = new HashMap() {{ put("locale", "en"); }}; try { // Fetch recipe page with slug "chocolate-cake" PageResponse pageResponse = client.getPage( "recipe", // page type slug "chocolate-cake", // page slug params, RecipePage.class // custom model class ); Page page = pageResponse.getData(); RecipePage recipe = page.getFields(); System.out.println("Recipe: " + recipe.getRecipeName()); System.out.println("Prep Time: " + recipe.getPrepTime() + " minutes"); System.out.println("Cook Time: " + recipe.getCookTime() + " minutes"); System.out.println("\nIngredients:"); for (String ingredient : recipe.getIngredients()) { System.out.println(" - " + ingredient); } System.out.println("\nInstructions:\n" + recipe.getInstructions()); // Access page metadata System.out.println("\nPage Slug: " + page.getSlug()); System.out.println("Status: " + page.getStatus()); System.out.println("Scheduled: " + page.getScheduled()); } catch (ButterCMSResponseException e) { System.err.println("Error fetching page: " + e.getMessage()); } ``` -------------------------------- ### Collections API Model Definition and Retrieval - Java Source: https://context7.com/buttercms/buttercms-java/llms.txt Shows Collections API implementation covering POJO model definition with Jackson annotations for JSON mapping, and collection retrieval with field filtering, sorting, and pagination. Includes proper getter/setter implementation and error handling for collection operations. ```java package com.example.model; import com.fasterxml.jackson.annotation.JsonProperty; public class Car { @JsonProperty("make") private String make; @JsonProperty("model") private String model; @JsonProperty("year") private int year; @JsonProperty("weight") private int weight; @JsonProperty("price") private double price; // Getters and setters public String getMake() { return make; } public void setMake(String make) { this.make = make; } public String getModel() { return model; } public void setModel(String model) { this.model = model; } public int getYear() { return year; } public void setYear(int year) { this.year = year; } public int getWeight() { return weight; } public void setWeight(int weight) { this.weight = weight; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } } ``` ```java import com.buttercms.model.CollectionResponse; import com.buttercms.model.Collection; import com.example.model.Car; import java.util.HashMap; import java.util.Map; Map params = new HashMap() {{ put("fields.weight", "400"); // Filter by weight field put("fields.year", "2020"); // Filter by year field put("order", "-price"); // Sort by price descending put("page", "1"); put("page_size", "10"); put("locale", "en"); put("levels", "2"); }}; try { CollectionResponse collectionResponse = client.getCollection( "cars", // collection slug params, Car.class ); Collection collection = collectionResponse.getData(); for (Car car : collection.getItems()) { System.out.println(car.getYear() + " " + car.getMake() + " " + car.getModel()); System.out.println(" Weight: " + car.getWeight() + " kg"); System.out.println(" Price: $" + car.getPrice()); } // Handle pagination PaginationMeta meta = collectionResponse.getMeta(); System.out.println("\nTotal items: " + meta.getCount()); } catch (ButterCMSResponseException e) { System.err.println("Error fetching collection: " + e.getMessage()); } ``` -------------------------------- ### List All Categories in Java Source: https://context7.com/buttercms/buttercms-java/llms.txt Retrieve all blog categories with optional recent posts. Displays category names and slugs along with post counts when recent posts are included. Handles API errors during retrieval. ```java import com.buttercms.model.CategoriesResponse; import com.buttercms.model.Category; import java.util.HashMap; import java.util.Map; Map params = new HashMap() {{ put("include", "recent_posts"); }}; try { CategoriesResponse categoriesResponse = client.getCategories(params); for (Category category : categoriesResponse.getData()) { System.out.println(category.getName() + " (" + category.getSlug() + ")"); if (category.getRecentPosts() != null) { System.out.println(" Posts: " + category.getRecentPosts().size()); } } } catch (ButterCMSResponseException e) { System.err.println("Error fetching categories: " + e.getMessage()); } ``` -------------------------------- ### Tags API Source: https://github.com/buttercms/buttercms-java/blob/master/README.md Endpoints for retrieving tag information. Includes methods to list all tags and retrieve a single tag by its slug. ```APIDOC ## GET /tags ### Description Retrieves a list of all tags. Supports query parameters for including related posts. ### Method GET ### Endpoint /tags ### Parameters #### Query Parameters - **include** (string) - Optional - If value is `recent_posts`, will return recent posts along with tags. ### Request Example ```java Map queryParams = new HashMap(){{ put("include","recent_posts"); ... }} TagsResponse tags = butterClient.getTags(queryParams); ``` ### Response #### Success Response (200) - **TagsResponse** - An object containing a list of tags. ## GET /tags/{slug} ### Description Retrieves a single tag by its unique slug. Allows inclusion of related posts. ### Method GET ### Endpoint /tags/{slug} ### Parameters #### Path Parameters - **slug** (string) - Required - The unique slug of the tag to retrieve. #### Query Parameters - **include** (string) - Optional - If value is `recent_posts`, will return recent posts along with the tag. ### Request Example ```java Map queryParams = new HashMap(){{ put("include","recent_posts"); ... }} TagResponse tag = butterClient.getTag("java",queryParams); ``` ### Response #### Success Response (200) - **TagResponse** - An object containing a single tag's details. ``` -------------------------------- ### Handle ButterCMS API Exceptions in Java Source: https://context7.com/buttercms/buttercms-java/llms.txt Demonstrates robust error handling for ButterCMS API requests in Java. It specifically catches `ButterCMSResponseException` for API-related errors (like 401, 404) and general `Exception` for other issues such as network problems. Requires the ButterCMS client and exception classes. ```java import com.buttercms.exception.ButterCMSResponseException; import com.buttercms.model.PostResponse; try { PostResponse post = client.getPost("non-existent-slug"); System.out.println(post.getData().getTitle()); } catch (ButterCMSResponseException e) { // Handle API errors (401 unauthorized, 404 not found, etc.) System.err.println("ButterCMS API Error: " + e.getMessage()); if (e.getMessage().contains("401")) { System.err.println("Invalid API token"); } else if (e.getMessage().contains("404")) { System.err.println("Resource not found"); } } catch (Exception e) { // Handle other exceptions (network errors, deserialization errors, etc.) System.err.println("Unexpected error: " + e.getMessage()); e.printStackTrace(); } ``` -------------------------------- ### List ButterCMS Pages in Java Source: https://github.com/buttercms/buttercms-java/blob/master/README.md Lists pages of a specific type from ButterCMS with support for filtering, sorting, pagination, and locale selection. The response is paginated and deserialized into a list of a specified Java class. ```java PagesResponse response = client.getPages("recipe", new HashMap() {{ put("page_size", "1"); }}, RecipePage.class) ``` -------------------------------- ### Categories API Source: https://github.com/buttercms/buttercms-java/blob/master/README.md Endpoints for retrieving category information. Includes methods to list all categories and retrieve a single category by its slug. ```APIDOC ## GET /categories ### Description Retrieves a list of all categories. Supports query parameters for including related posts. ### Method GET ### Endpoint /categories ### Parameters #### Query Parameters - **include** (string) - Optional - If value is `recent_posts`, will return recent posts along with categories. ### Request Example ```java Map queryParams = new HashMap(){{ put("include","recent_posts"); ... }} CategoriesResponse categories = butterClient.getCategories(queryParams); ``` ### Response #### Success Response (200) - **CategoriesResponse** - An object containing a list of categories. ## GET /categories/{slug} ### Description Retrieves a single category by its unique slug. Allows inclusion of related posts. ### Method GET ### Endpoint /categories/{slug} ### Parameters #### Path Parameters - **slug** (string) - Required - The unique slug of the category to retrieve. #### Query Parameters - **include** (string) - Optional - If value is `recent_posts`, will return recent posts along with categories. ### Request Example ```java Map queryParams = new HashMap(){{ put("include","recent_posts"); ... }} CategoryResponse category = butterClient.getCategory("java",queryParams); ``` ### Response #### Success Response (200) - **CategoryResponse** - An object containing a single category's details. ``` -------------------------------- ### Retrieve Single Tag Using ButterCMS Java Client Source: https://context7.com/buttercms/buttercms-java/llms.txt This snippet fetches a specific tag by slug, optionally including recent tagged posts, using the ButterCMS Java client. It requires the ButterCMS client instance and handles ButterCMSResponseException for errors. Inputs include tag slug and parameters like 'include=recent_posts'; outputs are Tag details and recent posts list. ```java import com.buttercms.model.TagResponse; import com.buttercms.model.Tag; import java.util.HashMap; import java.util.Map; Map params = new HashMap() {{ put("include", "recent_posts"); }}; try { TagResponse tagResponse = client.getTag("java", params); Tag tag = tagResponse.getData(); System.out.println("Tag: " + tag.getName()); System.out.println("Slug: " + tag.getSlug()); if (tag.getRecentPosts() != null) { System.out.println("\nRecent posts with this tag:"); tag.getRecentPosts().forEach(post -> { System.out.println(" - " + post.getTitle()); }); } } catch (ButterCMSResponseException e) { System.err.println("Error fetching tag: " + e.getMessage()); } ``` -------------------------------- ### List All Authors in Java Source: https://context7.com/buttercms/buttercms-java/llms.txt Retrieve a list of all authors with optional inclusion of their recent posts. Supports pagination and filtering through request parameters. Displays basic author information along with post counts when available. ```java import com.buttercms.model.AuthorsResponse; import com.buttercms.model.Author; import java.util.HashMap; import java.util.Map; Map params = new HashMap() {{ put("include", "recent_posts"); }}; try { AuthorsResponse authorsResponse = client.getAuthors(params); for (Author author : authorsResponse.getData()) { System.out.println(author.getFirstName() + " " + author.getLastName()); System.out.println(" Slug: " + author.getSlug()); System.out.println(" Email: " + author.getEmail()); if (author.getRecentPosts() != null) { System.out.println(" Posts: " + author.getRecentPosts().size()); } } } catch (ButterCMSResponseException e) { System.err.println("Error fetching authors: " + e.getMessage()); } ``` -------------------------------- ### Define Custom Page Model for ButterCMS Java Source: https://context7.com/buttercms/buttercms-java/llms.txt This POJO class defines a custom structure for ButterCMS page fields, such as for a recipe page, using Jackson annotations for deserialization. It includes properties like name, ingredients array, instructions, and times with getters/setters. Purpose is to map API responses to typed objects; no runtime dependencies beyond Jackson. ```java package com.example.model; import com.fasterxml.jackson.annotation.JsonProperty; public class RecipePage { @JsonProperty("recipe_name") private String recipeName; @JsonProperty("ingredients") private String[] ingredients; @JsonProperty("instructions") private String instructions; @JsonProperty("prep_time") private int prepTime; @JsonProperty("cook_time") private int cookTime; // Getters and setters public String getRecipeName() { return recipeName; } public void setRecipeName(String recipeName) { this.recipeName = recipeName; } public String[] getIngredients() { return ingredients; } public void setIngredients(String[] ingredients) { this.ingredients = ingredients; } public String getInstructions() { return instructions; } public void setInstructions(String instructions) { this.instructions = instructions; } public int getPrepTime() { return prepTime; } public void setPrepTime(int prepTime) { this.prepTime = prepTime; } public int getCookTime() { return cookTime; } public void setCookTime(int cookTime) { this.cookTime = cookTime; } } ``` -------------------------------- ### Authors API Source: https://github.com/buttercms/buttercms-java/blob/master/README.md Endpoints for retrieving author information. Includes methods to list all authors and retrieve a single author by their slug. ```APIDOC ## GET /authors ### Description Retrieves a list of all authors. Supports query parameters for filtering and including related data. ### Method GET ### Endpoint /authors ### Parameters #### Query Parameters - **include** (string) - Optional - If value is `recent_posts`, will return the author's recent posts in the response. ### Request Example ```java Map queryParams = new HashMap(){{ put("include","recent_posts"); ... }} AuthorsResponse authors = butterClient.getAuthors(queryParams); ``` ### Response #### Success Response (200) - **AuthorsResponse** - An object containing a list of authors and pagination metadata. ## GET /authors/{slug} ### Description Retrieves a single author by their unique slug. Allows inclusion of the author's recent posts. ### Method GET ### Endpoint /authors/{slug} ### Parameters #### Path Parameters - **slug** (string) - Required - The unique slug of the author to retrieve. #### Query Parameters - **include** (string) - Optional - If value is `recent_posts`, will return the author's recent posts in the response. ### Request Example ```java Map queryParams = new HashMap(){{ put("include","recent_posts"); ... }} AuthorResponse author = butterClient.getAuthor("john",queryParams); ``` ### Response #### Success Response (200) - **AuthorResponse** - An object containing a single author's details. ``` -------------------------------- ### Search ButterCMS Pages in Java Source: https://github.com/buttercms/buttercms-java/blob/master/README.md Searches pages within a specified page type from ButterCMS using a query string. Supports various filtering, sorting, pagination, and locale options. The results are paginated and deserialized into a list of a specified Java class. ```java Map queryParams = new HashMap(){{ put("query", "search query"); ... }} PagesResponse posts = butterClient.getSearchPages(queryParams); ``` -------------------------------- ### Collections API Source: https://github.com/buttercms/buttercms-java/blob/master/README.md Endpoint for retrieving items from a specified collection. ```APIDOC ## GET /collections/{collection_slug} ### Description Retrieves items from a specific collection based on its unique slug. Supports query parameters for filtering and pagination. ### Method GET ### Endpoint /collections/{collection_slug} ### Parameters #### Path Parameters - **collectionSlug** (string) - Required - The unique slug of the collection to retrieve items from. #### Query Parameters - **queryParams** (Map) - Optional - A map of additional query parameters for filtering and pagination. - **classType** (Class) - Required - The class type that the collection items will be deserialized into. ### Response #### Success Response (200) - **CollectionResponse<T>** - An object containing pagination metadata and a list of collection items of type T. ### Request Example ```java // Assuming T is a specific model class Map queryParams = new HashMap(); queryParams.put("limit", "10"); CollectionResponse items = butterClient.getCollection("products", queryParams, MyCollectionItem.class); ``` ``` -------------------------------- ### List Authors Source: https://github.com/buttercms/buttercms-java/blob/master/README.md Retrieves a list of all authors from ButterCMS. The response object contains a list of Author objects. Query parameters can be used for further filtering if needed. ```java AuthorsResponse authors = butterClient.getAuthors(queryParams); ``` -------------------------------- ### Retrieve Single Author in Java Source: https://context7.com/buttercms/buttercms-java/llms.txt Fetch detailed information about a specific author including their recent posts. Uses author slug as input parameter and supports including related data such as recent posts. Handles API exceptions during retrieval. ```java import com.buttercms.model.AuthorResponse; import com.buttercms.model.Author; import java.util.HashMap; import java.util.Map; Map params = new HashMap() {{ put("include", "recent_posts"); }}; try { AuthorResponse authorResponse = client.getAuthor("john-smith", params); Author author = authorResponse.getData(); System.out.println("Name: " + author.getFirstName() + " " + author.getLastName()); System.out.println("Email: " + author.getEmail()); System.out.println("Bio: " + author.getBio()); System.out.println("Title: " + author.getTitle()); System.out.println("Profile Image: " + author.getProfileImage()); System.out.println("Twitter: " + author.getTwitterHandle()); System.out.println("LinkedIn: " + author.getLinkedinUrl()); // Access recent posts if (author.getRecentPosts() != null) { System.out.println("\nRecent Posts:"); author.getRecentPosts().forEach(post -> { System.out.println(" - " + post.getTitle()); }); } } catch (ButterCMSResponseException e) { System.err.println("Error fetching author: " + e.getMessage()); } ``` -------------------------------- ### Retrieve Single ButterCMS Page in Java Source: https://github.com/buttercms/buttercms-java/blob/master/README.md Retrieves a single page of a specific type and slug from ButterCMS. Supports locale selection and deserializes the response into a specified Java class. ```java PageResponse recipe = client.getPage("recipe", "recipe-page-11", new HashMap() {{ put("locale", "en"); }}, RecipePage.class); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.