API Query Builder

The Bricksforge API Query Builder is a powerful tool that allows you to integrate external API data directly into your Bricks Builder projects. Create dynamic content from any API source, use automatic dynamic data tags, and optionally synchronize API data to WordPress Custom Post Types for better performance and searchability.

In this article, we will explain how to use the API Query Builder to connect to APIs, work with the data, and leverage advanced features like CPT synchronization.

Basic Concepts

The API Query Builder acts as a bridge between external data sources and Bricks Builder. It allows you to:

  • Connect to external APIs and display their data in your Bricks layouts
  • Use custom JSON data for static or testing purposes
  • Create automatic dynamic data tags for easy content integration
  • Synchronize API data to WordPress as Custom Post Types (v3.1.8)
  • Work with nested data structures through separate query loops
  • Control loading and caching for optimal performance

How It Works

  1. Configure an API endpoint in the Bricksforge settings
  2. Fetch and preview the API response data
  3. Select the endpoint in Bricks Builder query loops (just like WordPress posts or custom queries)
  4. Use dynamic data tags to display API fields in your design
  5. Optionally sync to CPTs for permanent storage and WordPress admin management

Getting Started

Creating Your First API Endpoint

  1. Navigate to Bricksforge > Features > API Query Builder in your WordPress admin
  2. Click “Add New API” in the sidebar
  3. Give your API a descriptive Name (e.g., “Product Catalog”)
  4. Choose your Source Type:
    • API Endpoint: For live external APIs
    • Custom JSON: For static data or testing

Simple Example: Public API

Let’s connect to a public API to display user data:

  1. Name: “Sample Users”
  2. Source Type: API Endpoint
  3. URL: https://jsonplaceholder.typicode.com/users
  4. Authentication: None
  5. Click Fetch to preview the data
  6. Enable “Create dynamic data tags automatically”
  7. Click Save

Now in Bricks Builder, you can:

  1. Add a Container element
  2. Set Query Loop to “Sample Users”
  3. Add Basic Text elements and use dynamic data tags like {brf_api_sample_users_name} and {brf_api_sample_users_email}

Source Types

API Endpoint

Use this option to connect to live external APIs. You’ll need:

  • A valid API URL
  • Authentication credentials (if required)
  • Understanding of the API’s response structure

When to use:

  • Real-time data that changes frequently
  • Third-party services (CRM, e-commerce, weather, etc.)
  • Data you want to refresh regularly

Custom JSON

Paste your JSON data directly into the textarea. The system will parse and use it as if it came from an API.

When to use:

  • Testing and development
  • Static data that rarely changes
  • Data from a one-time export
  • Prototyping before connecting to real APIs

Example Custom JSON:

[
  {
    "id": 1,
    "name": "Product One",
    "price": 29.99
  },
  {
    "id": 2,
    "name": "Product Two",
    "price": 39.99
  }
]

Authentication Methods

The API Query Builder supports multiple authentication methods to work with virtually any API.

None

For public APIs that don’t require authentication. Simply enter the URL and fetch the data.

Example APIs:

  • JSONPlaceholder (testing)
  • Public government data APIs
  • Open weather data

Basic Auth

Traditional username and password authentication. The system automatically creates the Base64-encoded header.

Configuration:

  1. Select Method: Basic Auth
  2. Enter your Username
  3. Enter your Password
  4. The header Authorization: Basic [encoded-credentials] is sent automatically

Common use cases:

  • Private WordPress REST APIs
  • Simple protected endpoints
  • Internal company APIs

Bearer Token

API key or OAuth token authentication. Supports both static and dynamic tokens.

Static Bearer Token

For APIs that provide a permanent API key.

Configuration:

  1. Select Method: Bearer Token
  2. Select Type: Static Token
  3. Enter your Token (the API key provided by the service)

The header Authorization: Bearer [your-token] is sent automatically.

Common use cases:

  • Most modern APIs (Stripe, SendGrid, etc.)
  • Services with dashboard-generated API keys

Dynamic Bearer Token

For APIs using OAuth-style authentication with token endpoints and refresh tokens.

Configuration:

  1. Select Method: Bearer Token
  2. Select Type: Dynamic Token
  3. Access Token Endpoint: URL where you request the initial token
  4. Access Token Key: Field name in the response (default: “accessToken”)
  5. Refresh Token Endpoint: URL to refresh expired tokens (optional)
  6. Refresh Token Key: Field name for refresh token (default: “refreshToken”)
  7. Send Auth Data As: Headers or Body Params
  8. Send Token As: Header (Bearer), Body Param, or Query Param

Add Authentication Data:

  • Click “Add Header” or “Add Body Param” to provide credentials
  • Example: Key: “username”, Value: “your-username”
  • Add as many fields as the token endpoint requires

How it works:

  1. On first request, the system calls your token endpoint with the credentials
  2. The received token is encrypted and stored
  3. All subsequent API requests use this token
  4. If a 401 error occurs, the token is automatically refreshed (if refresh endpoint is configured)
  5. The new token is stored and used for future requests

Common use cases:

  • OAuth 2.0 APIs
  • Enterprise APIs with expiring tokens
  • Services requiring periodic re-authentication

Custom Headers

For APIs using custom authentication schemes like API keys in specific headers.

Configuration:

  1. Select Method: Custom Headers
  2. Click “Add Header”
  3. Header Name: The exact header name (e.g., “X-API-Key”, “Api-Token”)
  4. Header Value: Your API key or token
  5. Add multiple headers as needed

Common use cases:

  • APIs with custom header requirements
  • Services using “X-API-Key” authentication
  • Multiple authentication headers

URL Configuration

API URL

Enter the complete endpoint URL. You can use:

  • Static URLs: https://api.example.com/products
  • Dynamic routes (see below): https://api.example.com/products/:id
  • Bricks dynamic data tags: https://api.example.com/products/{post_id}

Root Path

If your API returns nested data, use the Root Path to specify where the actual array of items is located.

Example API Response:

{
  "status": "success",
  "data": {
    "products": [
      { "id": 1, "name": "Product 1" },
      { "id": 2, "name": "Product 2" }
    ]
  }
}

Root Path: data/products or data.products

The system will navigate to that location and use the array found there as the loop data.

Dynamic Root Path: You can also use Bricks dynamic data tags in the root path: data/{custom_field_category}

This allows you to navigate to different parts of the response based on page data.

Dynamic Routes & Fallback Values

Using Dynamic Routes

Dynamic routes allow you to create flexible API URLs that change based on query parameters.

Syntax: Use :parameterName in your URL

Example:

https://api.example.com/users/:userId/posts

When a visitor navigates to yoursite.com/posts?userId=5, the system automatically replaces :userId with 5.

Multiple parameters:

https://api.example.com/:type/:id/details

Fallback Values

Fallback values are crucial for two reasons:

  1. Testing in settings: You need data to preview when configuring
  2. Builder mode: Bricks Builder needs sample data to render the layout

Configuration: When you enter a URL with dynamic routes or Bricks tags, a Fallback Values section appears automatically.

  1. Each dynamic parameter gets its own row
  2. Route: Shows the parameter name (read-only)
  3. Fallback Value: Enter a test value

Example:

  • Route: :userId → Fallback Value: 1
  • Route: :category → Fallback Value: electronics

Fetch URL example: If your fallback for :userId is 5, testing will use: https://api.example.com/users/5/posts

Frontend behavior: On the actual website, the system looks for the real query parameter. If not found, the page won’t make an API request (unless you’re in builder mode, where it uses the fallback).

Using Bricks Dynamic Data Tags

You can use any Bricks dynamic data tag in your URLs:

  • {post_id} - Current post ID
  • {user_id} - Current user ID
  • Custom fields: {acf_product_id}

Example:

https://api.example.com/product-details/{acf_product_sku}

This fetches different API data for each post based on its ACF field value.

Request Configuration

Custom Headers

Add custom headers to your API requests beyond authentication.

Common use cases:

  • Content-Type specification: Content-Type: application/json
  • Accept headers: Accept: application/json
  • Custom required headers: X-Custom-Header: value
  • API version headers: API-Version: 2.0

Configuration:

  1. Navigate to Request Headers section
  2. Click “Add Header”
  3. Enter Header Name and Header Value
  4. Add multiple headers as needed

Note: Authentication headers are managed in the Authentication section.

Query Parameters

Add URL query parameters to your requests.

Example URL with parameters:

https://api.example.com/products?limit=10&sort=price&order=desc

Configuration:

  1. Navigate to Query Params section
  2. Click “Add Query Param”
  3. Query Param Key: limit
  4. Query Param Value: 10
  5. Repeat for each parameter

Dynamic query parameters: You can use Bricks dynamic data tags in both keys and values:

  • Key: category
  • Value: {custom_field_product_category}

The system automatically URL-encodes the parameters.

Add WP Nonce

For WordPress REST API endpoints, enable “Use WP Nonce” to automatically include WordPress authentication.

When to enable:

  • Calling your own WordPress REST API
  • Accessing protected WordPress endpoints
  • Reading private post data via REST API

How it works:

  • Automatically adds X-WP-Nonce header
  • Sends WordPress cookies for authentication
  • Maintains user session context

Dynamic Data Tags

One of the most powerful features of the API Query Builder is automatic dynamic data tag creation.

Enabling Dynamic Data Tags

  1. In your API configuration, toggle “Create dynamic data tags automatically” to ON
  2. Fetch your API data to populate the tags
  3. Save your configuration

The system automatically creates dynamic data tags for every field in your API response.

Tag Naming Convention

Tags follow this format:

{brf_api_[api-name]_[field-name]}

Example: If your API is named “Products API” and returns a field called “productName”:

{brf_api_products_api_productname}

Nested fields use underscores to separate levels: API field: product.details.sku Tag: {brf_api_products_api_product_details_sku}

Using Tags in Bricks

  1. Add any Bricks element (Basic Text, Image, etc.)
  2. Click the dynamic data icon
  3. Find your API name in the groups list
  4. Select the field you want to display
  5. Or manually type: {brf_api_your_api_name_field_name}

Available in:

  • Text content
  • Image URLs
  • Link URLs
  • Custom attributes
  • Conditions
  • Element queries
  • Any field supporting dynamic data

Working with Nested Arrays

Many API responses contain nested arrays - arrays within the main data structure.

Example API Response:

[
  {
    "id": 1,
    "name": "Product One",
    "reviews": [
      { "author": "John", "rating": 5 },
      { "author": "Jane", "rating": 4 }
    ],
    "tags": ["electronics", "featured"]
  }
]

In this example, “reviews” and “tags” are nested arrays.

Selecting Nested Arrays

When you fetch API data containing nested arrays, a “Select Nested Arrays” section appears.

  1. Review the list of detected nested arrays
  2. Use “Select All” or “Deselect All” for bulk actions
  3. Check individual nested arrays you want to expose
  4. Click Save

Why select nested arrays?

  • Creates separate query loops in Bricks for nested data
  • Generates dynamic data tags for nested fields
  • Allows complex layouts with multiple data levels

Using Nested Array Query Loops

Once you’ve selected nested arrays, they appear as separate query types in Bricks.

Example:

  • Main query: “Products API”
  • Nested query: “Products API - Reviews”
  • Nested query: “Products API - Tags”

In Bricks Builder:

  1. Add a Block Element with query loop “Products API”
  2. Inside, add product name, price, etc.
  3. Add another Block Element (child of the first)
  4. Set its query loop to “Products API - Reviews”
  5. Display review author, rating, etc.

Result: Each product shows all its reviews in a nested loop.

Nested Array Dynamic Data Tags

Nested arrays use a double underscore (__) syntax:

{brf_api_products_api_reviews__author}
{brf_api_products_api_reviews__rating}

The double underscore indicates you’re accessing a field from the nested array.

Primitive Arrays

Some nested arrays contain simple values instead of objects:

"tags": ["electronics", "featured", "sale"]

For primitive arrays, use the special item placeholder:

{brf_api_products_api_tags__item}

This displays each tag value in the loop.

CPT Synchronization (v3.1.8)

The CPT (Custom Post Type) Synchronization feature allows you to store API data permanently in your WordPress database as custom post types.

Why Use CPT Sync?

Benefits:

  • Better performance: Data is stored locally, no API requests needed
  • WordPress admin access: Manage API data like regular posts
  • Search & filtering: Use WordPress’s built-in search and taxonomies
  • Offline access: Data remains available even if the API is down
  • Scheduled updates: Automatically refresh data on a schedule
  • Webhooks: Update on-demand when API data changes

When to use:

  • Product catalogs that don’t change frequently
  • Team member directories
  • Portfolio items from external sources
  • Any data you want users to search or filter
  • Data that should be SEO-indexed as individual pages

When NOT to use:

  • Real-time data that changes every second
  • Data with strict API terms of service restrictions

Important: Before enabling CPT Sync, ensure that storing and caching API data is permitted by the API provider’s terms of service. You are responsible for compliance with all data protection laws and API provider agreements.

Basic Setup

1. Enable CPT Sync

Toggle “Enable CPT Sync” to ON.

2. CPT Slug (Auto-Generated)

The system automatically generates a slug based on your API name:

  • API name: “Products API”
  • CPT slug: products_api
  • WordPress CPT: bfa_products_api

The bfa_ prefix identifies it as a Bricksforge API-synced post type.

Note: The slug is read-only and generated automatically.

3. Unique Identifier Field

Critical setting: Select which field uniquely identifies each item in your API response.

Examples of good unique identifiers:

  • id - Numeric ID from the API
  • sku - Product SKU
  • slug - URL-friendly identifier
  • email - For user data
  • uuid - Unique identifier strings

Why it matters: The sync process uses this field to:

  • Detect if an item already exists (update vs. create)
  • Match API items to WordPress posts
  • Delete posts when items are removed from the API

Choose carefully:

  • The field must be truly unique for each item
  • It should never change for an item
  • It must always be present in the API response

Field Mapping

Map API fields to WordPress post fields.

Post Title ← API Field

Select which API field should become the post title.

Examples:

  • name → Product name
  • title → Article title
  • full_name → Person’s name

Tip: Choose a descriptive field that will look good in WordPress admin lists.

Post Content ← API Field

Select which API field should become the post content.

Examples:

  • description → Product description
  • content → Article content
  • bio → Team member biography

Tip: Choose a field with longer text content. Can be left empty if not needed.

Other Fields (Automatic)

All other API fields are automatically stored as custom fields with the prefix brf_field_.

Example:

  • API field: price → Custom field: brf_field_price
  • API field: rating → Custom field: brf_field_rating

Access in Bricks: Use dynamic data tags like {cf_brf_field_price} to display these values.

Sync Scheduling

Control when and how often your API data syncs to WordPress.

Preset Intervals

Choose from common sync intervals:

  • Every 5 minutes: Very frequent updates (high API usage)
  • Every 15 minutes: Frequent updates
  • Every 30 minutes: Regular updates
  • Every hour: Hourly refresh
  • Every 6 hours: Four times per day
  • Every 24 hours: Daily sync (recommended for most use cases)

Custom Cron Expression

Select “Custom” to enter your own cron expression.

Format: minute hour day month weekday

Examples:

  • 0 0 * * * - Every day at midnight
  • 0 */6 * * * - Every 6 hours
  • 0 9,17 * * 1-5 - 9 AM and 5 PM on weekdays
  • */15 * * * * - Every 15 minutes

Resources: Use crontab.guru to build and understand cron expressions.

Note: WordPress uses its own cron system (WP-Cron), which runs when your site receives visits. For critical syncs, consider setting up a real server cron.

Manual Sync

Click the “Sync Now” button to trigger an immediate sync without waiting for the scheduled time.

When to use:

  • Testing your configuration
  • Immediately after changing API settings
  • When you know the API data has changed
  • Before launching a new feature

Sync process:

  1. Button shows “Syncing…” with a spinner
  2. System fetches fresh API data
  3. Compares with existing posts
  4. Creates new posts
  5. Updates changed posts
  6. Deletes removed posts
  7. Shows sync statistics

Deleting CPTs and Data

You can delete all CPTs and their associated data for a specific API endpoint at any time.

Access the delete function:

  1. Open the API endpoint you want to clean up
  2. Click the Actions button (three dots icon) next to “Clear Cache”
  3. Select “Delete CPTs & Data” from the dropdown menu

What gets deleted:

  • All posts in the main CPT for this API endpoint
  • All posts in child CPTs associated with this endpoint
  • All metadata and custom fields related to these posts

Important notes:

  • ⚠️ This action cannot be undone - all data will be permanently deleted
  • Only CPTs and data for the currently selected API endpoint will be deleted
  • CPTs from other API endpoints remain untouched
  • The CPT type itself remains registered but will be empty
  • You’ll see a confirmation dialog before deletion proceeds

When to use:

  • Starting fresh with a new sync configuration
  • Removing test data before going live
  • Cleaning up after changing API structure significantly
  • Freeing up database space when CPT sync is no longer needed

After deletion:

  • The sync statistics will be reset
  • You can start a new sync to repopulate the CPTs
  • The CPT type registration remains, so you can sync again without reconfiguration

Child CPTs/Taxonomies from Nested Arrays

Create separate post types or taxonomies for nested array data within your API response. For primitive arrays (tags, categories), you can create WordPress taxonomies instead of CPTs for better semantic structure.

Example scenario: Your products API returns:

{
  "id": 1,
  "name": "Laptop",
  "reviews": [
    { "id": 101, "author": "John", "rating": 5, "text": "Great!" },
    { "id": 102, "author": "Jane", "rating": 4, "text": "Good" }
  ]
}

You can create:

  1. Parent CPT: bfa_products (main product posts)
  2. Child CPT: bfa_products_reviews (review posts linked to products)

Enabling Child CPTs/Taxonomies

  1. Ensure nested arrays are available (fetch API data first)
  2. In the Child CPTs/Taxonomies from Nested Arrays section, you’ll see all detected nested arrays
  3. Check the checkbox next to the nested array (e.g., “Reviews” or “Tags”)
  4. Configuration options appear

Configuring Child CPTs

Child CPT Label: Enter a human-readable name for this post type.

  • Example: “Product Reviews”
  • Appears in WordPress admin menu

For Object Arrays:

If your nested array contains objects, configure:

Unique ID Field: Select which field uniquely identifies each nested item.

  • Example: Select id or review_id
  • Must be unique across all reviews
  • Used to detect updates vs. new items

Available fields: The dropdown shows all fields from the first item in your nested array.

For Primitive Arrays:

If your nested array contains simple values (strings, numbers):

"tags": ["electronics", "featured", "sale"]
"categories": ["Laptops", "Gaming", "Office"]

You have two options:

Option 1: Taxonomy (Recommended)

Create a WordPress taxonomy for better semantic structure:

  1. Select Type: “Taxonomy”
  2. Each value becomes a taxonomy term
  3. Terms are automatically linked to parent posts
  4. Hierarchical option: Enable for category-like behavior (parent-child terms)

Benefits of taxonomies:

  • Native WordPress filtering and querying
  • Better for tags, categories, classifications
  • Appears in WordPress admin columns
  • Works with WordPress taxonomy functions

Example:

  • “electronics”, “featured”, “sale” become taxonomy terms
  • Query all products with “electronics” tag using standard WordPress taxonomy queries

Option 2: Child CPT

Create posts for each primitive value:

  1. Select Type: “Child CPT”
  2. Each value becomes a post
  3. The value is used as both unique ID and content
  4. No additional configuration needed

When to use CPT instead of Taxonomy:

  • When you need custom fields for each value
  • When you want full post features (revisions, featured images, etc.)

How Child CPTs Work

Sync process:

  1. Main items sync to parent CPT posts
  2. For each parent post, nested arrays are processed
  3. Child posts are created in the child CPT
  4. Automatic relationship: Child posts are linked to their parent via post_parent

WordPress admin:

  • Parent and child CPTs appear as separate menu items
  • View all reviews across all products

In Bricks Builder:

For Child CPTs:

  1. Query parent CPT: “Products”
  2. Inside, query child CPT: “Product Reviews”
  3. In the child query loop, set the Meta Query to
    • Meta-Key: brf_field_parent_id or _brf_parent_post_id
    • Meta Value: is the ID of the parent post.
  4. Display nested data just like regular posts

For Taxonomies:

  1. Query parent CPT: “Products”
  2. Use Terms dynamic data to display taxonomy terms
  3. Filter products by taxonomy using Tax Query
    • Taxonomy: Select your custom taxonomy (e.g., bfa_products_tags)
    • Terms: Select specific terms or use dynamic data
  4. Create taxonomy archives for browsing by term

Benefits:

Child CPTs:

  • Nested data becomes searchable
  • Create dedicated layouts for nested items
  • Full custom field support

Taxonomies:

  • Native WordPress taxonomy features
  • Better performance for filtering
  • Automatic archives and term pages
  • Works with standard WordPress functions
  • Use WordPress post relationships
  • Filter and sort nested data

Webhook Integration

Webhooks allow external systems to trigger a sync on-demand, perfect for real-time updates.

Enabling Webhooks

  1. Toggle “Enable Webhook” to ON
  2. A unique webhook URL and secret are automatically generated

Webhook URL

Your unique endpoint:

https://yoursite.com/wp-json/bricksforge/v1/api-sync-webhook/[your-item-id]

Use this URL to trigger syncs from:

  • Your API provider’s webhook settings
  • Third-party automation tools (Zapier, Make, etc.)
  • Your own backend systems
  • CI/CD pipelines

Webhook Secret

A randomly generated security token.

Security: All webhook requests must include this secret in a header to be accepted.

Format:

X-Webhook-Secret: your-generated-secret-here

Why it’s needed: Without the secret, anyone could trigger syncs to your site, wasting server resources or potentially causing issues.

Triggering a Webhook

Using cURL:

curl -X POST \
  https://yoursite.com/wp-json/bricksforge/v1/api-sync-webhook/abc123 \
  -H 'X-Webhook-Secret: your-secret-here'

Using JavaScript:

fetch("https://yoursite.com/wp-json/bricksforge/v1/api-sync-webhook/abc123", {
  method: "POST",
  headers: {
    "X-Webhook-Secret": "your-secret-here",
  },
});

Webhook Response

Success (200):

{
  "success": true,
  "message": "Sync triggered successfully",
  "stats": {
    "added": 3,
    "updated": 5,
    "deleted": 1
  }
}

Error (401 - Invalid secret):

{
  "success": false,
  "message": "Invalid webhook secret"
}

Error (404 - Invalid item):

{
  "success": false,
  "message": "API configuration not found"
}

Admin Menu Settings

Control how your CPT appears in WordPress admin.

Create Admin Menu Item

Toggle “Create Admin Menu Item” to ON.

When enabled:

  • Your CPT appears as a top-level menu in WordPress admin

When disabled:

  • CPT is registered but has no admin menu
  • Posts still exist and are queryable
  • Useful for purely frontend-driven data

Tip: Enable this if you or your clients need to manage or view synced data in the admin.

Sync Statistics

After each sync (manual or scheduled), statistics are displayed.

Metrics shown:

  • Added: New posts created from new API items
  • Updated: Existing posts updated with changed data
  • Deleted: Posts removed because items no longer exist in API
  • Errors: Any items that failed to sync

Success message:

Sync completed successfully! Added: 3, Updated: 5, Deleted: 1

Error message:

Sync completed with errors. Added: 3, Updated: 5, Deleted: 0. Check errors below.

Error list: If errors occurred, each is listed with details:

  • Item identifier that failed
  • Error message
  • Reason for failure

Common errors:

  • Invalid unique identifier (duplicates)
  • Missing required field data
  • API timeout during sync
  • Database write failure

Troubleshooting:

  • Check API response for consistency
  • Verify unique identifier field is always present
  • Increase PHP timeout limits for large syncs
  • Check WordPress error logs

Caching

Control how long API responses are cached to optimize performance.

Cache Lifetime

Set the cache duration in hours.

Examples:

  • 0.1 = 6 minutes
  • 1 = 1 hour
  • 24 = 1 day
  • 168 = 1 week

Default behavior:

  • In Bricks Builder: Short cache (5 seconds) for testing
  • On frontend: Specified cache lifetime

How it works:

  1. First request fetches data from API
  2. Response is cached using WordPress transients
  3. Subsequent requests use cached data
  4. After cache expires, next request fetches fresh data

When to Use Short Cache Times

  • Data changes frequently (stock prices, weather)
  • Testing and development
  • User-specific data
  • Real-time applications

Example: 0.25 (15 minutes)

When to Use Long Cache Times

  • Static data that rarely changes
  • Data that updates on a schedule
  • Heavy API rate limits
  • Expensive API calls

Example: 24 (24 hours) or longer

Clearing Cache Manually

Click “Clear Cache” to immediately invalidate cached data.

When to clear cache:

  • After changing API settings
  • After updating authentication
  • When you know API data has changed
  • Testing with fresh data

What happens:

  • Cached response is deleted
  • Next request fetches fresh data from API
  • New cache is created with fresh data

Note: Clearing cache doesn’t affect CPT synced data. For that, use “Sync Now”.

Loading Types

Control how query loops load data, especially useful for large datasets.

All (Default)

Loads the complete API response at once.

Pros:

  • Simple setup
  • All data immediately available
  • Standard Bricks pagination works
  • No additional API configuration needed

Cons:

  • Can be slow for large datasets
  • Uses more memory
  • Single large API request

Best for:

  • Small to medium datasets (under 100 items)
  • APIs without pagination support
  • Simple use cases

Infinite Scroll

Progressively loads more data as users scroll down the page.

Pros:

  • Fast initial page load
  • Better user experience for large datasets
  • Reduces API load
  • Modern scrolling experience

Cons:

  • Requires API pagination support
  • More complex setup
  • May not work with all APIs

Configuration:

  1. Select Loading Type: “Infinite Scroll”
  2. Count of items to load: How many items per request (e.g., 10)
  3. Total Key: API field containing total results count (e.g., total)
  4. Limit Key: API parameter for items per page (e.g., limit)
  5. Offset Key: API parameter for starting position (e.g., offset or page)

API requirements: Your API must support pagination parameters and return total count.

Example API request:

https://api.example.com/products?limit=10&offset=0

Example API response:

{
  "total": 250,
  "limit": 10,
  "offset": 0,
  "results": [
    {"id": 1, "name": "Product 1"},
    ...
  ]
}

How it works:

  1. Initial load: Fetches first 10 items (offset=0)
  2. User scrolls to bottom
  3. Automatic request: Fetches next 10 items (offset=10)
  4. Repeat until all items loaded or user stops

Note: Set your Root Path to point to the results array, not the whole response.

Conditional Loading

Control where and when API requests are made to optimize performance.

Why it matters: Every time the conditions are met, an API request is made. Loading everywhere can:

  • Slow down your site
  • Exceed API rate limits
  • Waste server resources
  • Cost money (paid APIs)

Best practice: Only load API data where it’s actually used.

Load On: Everywhere

API requests are made on every page of your site.

Except on these pages: Optionally exclude specific pages from loading.

  1. Select “Load on”: Everywhere
  2. Choose pages in “Except on these pages”
  3. Selected pages will not trigger API requests

When to use:

  • Site-wide header/footer data
  • Global navigation elements
  • Data needed on every page

Warning: Be cautious with this option. It can generate many API requests.

Load On: Specific Pages

API requests only on selected pages.

Configuration:

  1. Select “Load on”: Specific Pages
  2. Select pages in the “Pages” dropdown
  3. Only these pages will trigger API requests

When to use:

  • Product catalog on product pages only
  • Team members on about page
  • Portfolio items on portfolio page

Recommended: This is the most common and efficient option.

Load On: Specific Templates

API requests only when specific Bricks templates are active.

Configuration:

  1. Select “Load on”: Specific Templates
  2. Select templates in the “Templates” dropdown
  3. Only pages using these templates will trigger requests

When to use:

  • Data tied to template types
  • Single post templates
  • Archive templates
  • Header/footer templates

Example: Load product API data only on pages using your “Single Product” template.

Load On: Custom Post IDs

API requests only for specific post IDs.

Configuration:

  1. Select “Load on”: Custom Post IDs
  2. Enter comma-separated post IDs: 45, 67, 89
  3. Only these specific posts trigger requests

When to use:

  • Landing pages with special data
  • Specific product pages
  • Testing on staging posts

Example: 123, 456, 789

Performance Tips

  1. Be specific: The narrower your conditions, the better
  2. Avoid “Everywhere”: Unless absolutely necessary
  3. Test in builder: Conditions work in builder mode too
  4. Combine with caching: Long cache + specific pages = optimal
  5. Monitor usage: Check your API provider’s usage dashboard

Troubleshooting

Authentication Errors (401)

Error message: “401: The API request failed because of authentication error.”

Possible causes:

  • Incorrect API key or token
  • Expired token (dynamic tokens)
  • Wrong authentication method selected
  • Malformed authorization header

Solutions:

  1. Verify your credentials in the API provider dashboard
  2. For bearer tokens, ensure you copied the complete token
  3. Check if your token has expired (regenerate if needed)
  4. Try different authentication methods if unsupported
  5. For dynamic tokens, verify token endpoint URL is correct
  6. Check if API requires specific headers beyond authentication

Testing: Use the “Fetch” button to test. If it fails, check the error message in the sidebar.

Invalid JSON Responses

Error message: “The API response is not valid JSON.”

Possible causes:

  • API returned HTML instead of JSON
  • API returned XML or CSV
  • API is down or returning error pages
  • Incorrect URL or endpoint

Solutions:

  1. Check the URL in your browser - does it return JSON?
  2. Look at response headers - is Content-Type application/json?
  3. For XML APIs, the system auto-detects XML (no action needed)
  4. For CSV APIs, ensure Content-Type is text/csv
  5. Verify the API is operational
  6. Check if you need authentication (public vs. private endpoints)

Advanced: View the raw response in browser developer tools:

curl -i https://your-api-url

Dynamic Routes Not Working

Issue: Dynamic routes like :id aren’t being replaced.

Possible causes:

  • Missing query parameter in URL
  • No fallback value configured
  • Incorrect parameter name
  • Not on a page that provides the parameter

Solutions:

  1. Verify fallback values are set for builder/testing
  2. Check the actual page URL includes the parameter: ?id=123
  3. Ensure parameter name matches exactly (case-sensitive)
  4. For Bricks tags {post_id}, verify the post has that field
  5. Test the full URL with parameters in your browser

Example: URL: https://api.example.com/users/:userId Fallback: userId = 1 Frontend: yoursite.com/page?userId=5

Sync Failures

Issue: CPT sync not creating or updating posts.

Possible causes:

  • No unique identifier field selected
  • Unique identifier field missing from API data
  • Unique identifier has duplicate values
  • API timeout during sync
  • PHP memory limit reached
  • Database connection issues

Solutions:

  1. Verify unique ID field: Ensure it’s selected and always present
  2. Check API response: Fetch data and verify the field exists
  3. Test uniqueness: Ensure no two items share the same ID
  4. Increase timeout: Add to wp-config.php:
    set_time_limit(300); // 5 minutes
  5. Increase memory: Add to wp-config.php:
    define('WP_MEMORY_LIMIT', '256M');
  6. Check error logs: Look in WordPress debug.log for specific errors
  7. Sync smaller batches: Use conditions to sync fewer items first
  8. Review sync statistics: Check which step failed

Missing Dynamic Data Tags

Issue: Dynamic data tags don’t appear in Bricks Builder.

Possible causes:

  • “Create dynamic data tags” is disabled
  • No API data fetched yet
  • API status is “inactive”
  • Cache needs refresh

Solutions:

  1. Enable “Create dynamic data tags automatically”
  2. Click “Fetch” to load API data
  3. Set status to “Active”
  4. Save your configuration
  5. Clear cache: “Clear Cache” button
  6. Refresh Bricks Builder (hard refresh: Ctrl+F5)
  7. Verify API is saved (click “Save” in sidebar)

Note: Changes to dynamic data tags require saving the API configuration.

Cache Issues

Issue: Seeing old data despite API changes.

Possible causes:

  • Cache hasn’t expired yet
  • Multiple cache layers (plugin, server, CDN)
  • Transient cache stuck
  • CPT data not synced

Solutions:

  1. Click “Clear Cache” for this API
  2. For CPT synced data, click “Sync Now”
  3. Clear all WordPress caches (if using cache plugin)
  4. Clear object cache if using Redis/Memcached
  5. Purge CDN cache if applicable
  6. Check cache lifetime setting (maybe it’s too long)
  7. Set cache to 0 temporarily for testing

Developer check:

// Check if transient exists
$cache_key = 'brf_api_' . $item_id;
$cached = get_transient($cache_key);
var_dump($cached);

Nested Arrays Not Appearing

Issue: Nested arrays don’t show as separate query loops.

Possible causes:

  • Nested arrays not selected
  • API structure doesn’t contain arrays
  • Arrays are empty in the response
  • Need to save configuration

Solutions:

  1. Fetch API data first (click “Fetch”)
  2. Look for “Select Nested Arrays” section
  3. Check the boxes for nested arrays you want
  4. Click “Save”
  5. Refresh Bricks Builder
  6. Look for “API Name - Nested Array Name” in query types

Verify structure: Your API response must contain actual arrays:

{
  "id": 1,
  "name": "Item",
  "nested": [
    // This is a nested array
    { "field": "value" }
  ]
}

Not just nested objects:

{
  "id": 1,
  "nested": {
    // This is NOT a nested array
    "field": "value"
  }
}

Best Practices

Performance Optimization

1. Use appropriate cache lifetimes

  • Frequently changing data: 15-60 minutes
  • Daily updates: 24 hours
  • Static data: 1 week or more

2. Leverage conditional loading

  • Only load where needed
  • Avoid “Load everywhere” unless necessary
  • Use specific pages or templates

3. Consider CPT sync for better performance

  • Eliminates frontend API requests
  • Data served from WordPress database
  • Faster page loads
  • Better for SEO

4. Optimize API responses

  • Use Root Path to skip unnecessary data
  • Request only needed fields (if API supports it)
  • Use pagination for large datasets

5. Limit nested arrays

  • Only enable nested arrays you’ll actually use
  • More nested arrays = more processing
  • Consider child CPTs for complex nested data

Security Considerations

1. Protect API keys

  • Never commit credentials to version control
  • Use environment variables when possible
  • Rotate keys regularly
  • Limit key permissions at API provider

2. Authentication

  • Always use authentication for private APIs
  • Prefer bearer tokens over basic auth
  • Use dynamic tokens for OAuth APIs
  • Store tokens securely (automatic encryption)

3. Webhook security

  • Always require webhook secret
  • Never share webhook URLs publicly
  • Regenerate secret if compromised
  • Use HTTPS for all webhook endpoints

4. Data validation

  • Verify API responses before processing
  • Check unique identifiers for validity
  • Sanitize data before displaying
  • Use Bricks’ built-in escaping

5. Rate limiting

  • Respect API provider limits
  • Use appropriate cache times
  • Avoid excessive manual fetching
  • Monitor API usage

When to Use CPT Sync vs Dynamic Loading

Use CPT Sync when:

  • Data updates on a schedule (daily, hourly)
  • You need WordPress search/filtering
  • SEO and individual post pages are important
  • Data should be manageable in WP admin
  • API has rate limits
  • Performance is critical

Use Dynamic Loading when:

  • Data changes in real-time
  • You don’t need post pages
  • Data is for display only
  • API supports high request rates
  • Caching is sufficient
  • Dataset is small

Use both:

  • Sync for main content (products, posts)
  • Dynamic loading for real-time elements (stock, weather)
  • Best of both worlds

Structuring API Responses

Best practices for API response structure:

1. Use consistent field names

// Good
{"id": 1, "name": "Item"}

// Avoid
{"ID": 1, "ITEMNAME": "Item"}

2. Use arrays for repeating data

// Good
{"products": [{"name": "A"}, {"name": "B"}]}

// Avoid
{"product1": {"name": "A"}, "product2": {"name": "B"}}

3. Include unique identifiers

// Always include
{ "id": 123, "sku": "ABC123", "name": "Product" }

4. Use consistent data types

// Good
{"price": 29.99, "stock": 5}

// Avoid
{"price": "29.99", "stock": "5"}

5. Organize with root paths

{
  "meta": { "status": "ok", "count": 2 },
  "data": [
    { "id": 1, "name": "Item 1" },
    { "id": 2, "name": "Item 2" }
  ]
}

Set Root Path to data for cleaner loops.

Error Handling Strategies

1. Provide fallback content Use Bricks conditions to show alternative content if API fails:

  • Check if dynamic data tag has value
  • Show “Coming soon” or placeholder
  • Use static content as backup

2. Monitor sync statistics

  • Check sync stats after each run
  • Set up notifications for errors
  • Keep log of failed syncs
  • Review error messages regularly

3. Test thoroughly

  • Test all authentication methods
  • Test with missing fields
  • Test with malformed data
  • Test with API down scenarios
  • Test cache clearing

4. Plan for API downtime

  • Use longer cache times
  • Enable CPT sync for critical data
  • Have static fallback pages
  • Communicate with users during issues

5. Log strategically Enable WordPress debugging during setup:

// wp-config.php
define('WP_DEBUG', true);
define('WP_DEBUG_LOG', true);
define('WP_DEBUG_DISPLAY', false);

Review logs at wp-content/debug.log

Advanced Usage

Custom Filters and Hooks

The API Query Builder provides several filters for developers.

Modify request headers:

add_filter('bricksforge/api_query_builder/request_headers', function($headers) {
    $headers['Custom-Header'] = 'custom-value';
    return $headers;
}, 10, 1);

Modify request URL:

add_filter('bricksforge/api_query_builder/request_url', function($url) {
    // Add custom logic
    return $url;
}, 10, 1);

Modify API response:

add_filter('bricksforge/api_query_builder/response', function($response) {
    // Transform response data
    return $response;
}, 10, 1);

Modify token request headers:

add_filter('bricksforge/api_query_builder/retrieve_token_request_headers', function($headers, $item) {
    // Customize token request
    return $headers;
}, 10, 2);

Modify token request body:

add_filter('bricksforge/api_query_builder/retrieve_token_request_body', function($body, $item) {
    // Customize token request body
    return $body;
}, 10, 2);

Google Sheets Integration

The API Query Builder has special support for Google Sheets.

Setup:

  1. Make your sheet public or get a share link
  2. Use the Google Sheets API URL format:
    https://sheets.googleapis.com/v4/spreadsheets/SHEET_ID/values/RANGE?key=API_KEY
  3. First row = headers (automatically mapped)
  4. Subsequent rows = data

Example: Sheet with columns: Name, Email, Phone Automatically creates tags:

  • {brf_api_sheet_name_name}
  • {brf_api_sheet_name_email}
  • {brf_api_sheet_name_phone}

Working with CSV APIs

APIs returning CSV are automatically detected and parsed.

Requirements:

  • Content-Type: text/csv
  • First row = headers
  • Subsequent rows = data

Note: No special configuration needed; parsing is automatic.

Working with XML APIs

APIs returning XML are automatically detected and converted to arrays.

Requirements:

  • Content-Type: text/xml or application/xml
  • Valid XML structure

Note: XML is converted to nested arrays automatically.

Support

If you encounter issues not covered in this documentation:

  1. Community forum: Reach out to other users
  2. Support ticket: Contact Bricksforge support
  3. WordPress debug logs: Enable debugging for detailed error messages

Summary

The API Query Builder is a comprehensive tool for integrating external data into your Bricks Builder projects. Key takeaways:

  • Easy setup: Configure APIs with or without authentication
  • Flexible data sources: API endpoints or custom JSON
  • Automatic integration: Dynamic data tags and query loops
  • Performance options: Caching, conditional loading, infinite scroll
  • Permanent storage: CPT sync for WordPress integration
  • Advanced features: Nested arrays, child CPTs, webhooks
  • Data management: Manual sync, scheduled sync, and delete functionality
  • Production ready: Security, error handling, monitoring

Whether you’re displaying a simple product feed or building a complex data-driven application, the API Query Builder provides the tools you need to succeed.