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
- Configure an API endpoint in the Bricksforge settings
- Fetch and preview the API response data
- Select the endpoint in Bricks Builder query loops (just like WordPress posts or custom queries)
- Use dynamic data tags to display API fields in your design
- Optionally sync to CPTs for permanent storage and WordPress admin management
Getting Started
Creating Your First API Endpoint
- Navigate to Bricksforge > Features > API Query Builder in your WordPress admin
- Click âAdd New APIâ in the sidebar
- Give your API a descriptive Name (e.g., âProduct Catalogâ)
- 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:
- Name: âSample Usersâ
- Source Type: API Endpoint
- URL:
https://jsonplaceholder.typicode.com/users - Authentication: None
- Click Fetch to preview the data
- Enable âCreate dynamic data tags automaticallyâ
- Click Save
Now in Bricks Builder, you can:
- Add a Container element
- Set Query Loop to âSample Usersâ
- 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:
- Select Method: Basic Auth
- Enter your Username
- Enter your Password
- 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:
- Select Method: Bearer Token
- Select Type: Static Token
- 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:
- Select Method: Bearer Token
- Select Type: Dynamic Token
- Access Token Endpoint: URL where you request the initial token
- Access Token Key: Field name in the response (default: âaccessTokenâ)
- Refresh Token Endpoint: URL to refresh expired tokens (optional)
- Refresh Token Key: Field name for refresh token (default: ârefreshTokenâ)
- Send Auth Data As: Headers or Body Params
- 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:
- On first request, the system calls your token endpoint with the credentials
- The received token is encrypted and stored
- All subsequent API requests use this token
- If a 401 error occurs, the token is automatically refreshed (if refresh endpoint is configured)
- 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:
- Select Method: Custom Headers
- Click âAdd Headerâ
- Header Name: The exact header name (e.g., âX-API-Keyâ, âApi-Tokenâ)
- Header Value: Your API key or token
- 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:
- Testing in settings: You need data to preview when configuring
- 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.
- Each dynamic parameter gets its own row
- Route: Shows the parameter name (read-only)
- 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:
- Navigate to Request Headers section
- Click âAdd Headerâ
- Enter Header Name and Header Value
- 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:
- Navigate to Query Params section
- Click âAdd Query Paramâ
- Query Param Key:
limit - Query Param Value:
10 - 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-Nonceheader - 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
- In your API configuration, toggle âCreate dynamic data tags automaticallyâ to ON
- Fetch your API data to populate the tags
- 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
- Add any Bricks element (Basic Text, Image, etc.)
- Click the dynamic data icon
- Find your API name in the groups list
- Select the field you want to display
- 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.
- Review the list of detected nested arrays
- Use âSelect Allâ or âDeselect Allâ for bulk actions
- Check individual nested arrays you want to expose
- 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:
- Add a Block Element with query loop âProducts APIâ
- Inside, add product name, price, etc.
- Add another Block Element (child of the first)
- Set its query loop to âProducts API - Reviewsâ
- 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
Legal Notice
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 APIsku- Product SKUslug- URL-friendly identifieremail- For user datauuid- 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 nametitleâ Article titlefull_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 descriptioncontentâ Article contentbioâ 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 midnight0 */6 * * *- Every 6 hours0 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:
- Button shows âSyncingâŚâ with a spinner
- System fetches fresh API data
- Compares with existing posts
- Creates new posts
- Updates changed posts
- Deletes removed posts
- 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:
- Open the API endpoint you want to clean up
- Click the Actions button (three dots icon) next to âClear Cacheâ
- 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:
- Parent CPT:
bfa_products(main product posts) - Child CPT:
bfa_products_reviews(review posts linked to products)
Enabling Child CPTs/Taxonomies
- Ensure nested arrays are available (fetch API data first)
- In the Child CPTs/Taxonomies from Nested Arrays section, youâll see all detected nested arrays
- Check the checkbox next to the nested array (e.g., âReviewsâ or âTagsâ)
- 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
idorreview_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:
- Select Type: âTaxonomyâ
- Each value becomes a taxonomy term
- Terms are automatically linked to parent posts
- 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:
- Select Type: âChild CPTâ
- Each value becomes a post
- The value is used as both unique ID and content
- 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:
- Main items sync to parent CPT posts
- For each parent post, nested arrays are processed
- Child posts are created in the child CPT
- 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:
- Query parent CPT: âProductsâ
- Inside, query child CPT: âProduct Reviewsâ
- In the child query loop, set the Meta Query to
- Meta-Key:
brf_field_parent_idor_brf_parent_post_id - Meta Value: is the ID of the parent post.
- Meta-Key:
- Display nested data just like regular posts
For Taxonomies:
- Query parent CPT: âProductsâ
- Use Terms dynamic data to display taxonomy terms
- 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
- Taxonomy: Select your custom taxonomy (e.g.,
- 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
- Toggle âEnable Webhookâ to ON
- 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 minutes1= 1 hour24= 1 day168= 1 week
Default behavior:
- In Bricks Builder: Short cache (5 seconds) for testing
- On frontend: Specified cache lifetime
How it works:
- First request fetches data from API
- Response is cached using WordPress transients
- Subsequent requests use cached data
- 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:
- Select Loading Type: âInfinite Scrollâ
- Count of items to load: How many items per request (e.g.,
10) - Total Key: API field containing total results count (e.g.,
total) - Limit Key: API parameter for items per page (e.g.,
limit) - Offset Key: API parameter for starting position (e.g.,
offsetorpage)
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:
- Initial load: Fetches first 10 items (offset=0)
- User scrolls to bottom
- Automatic request: Fetches next 10 items (offset=10)
- 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.
- Select âLoad onâ: Everywhere
- Choose pages in âExcept on these pagesâ
- 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:
- Select âLoad onâ: Specific Pages
- Select pages in the âPagesâ dropdown
- 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:
- Select âLoad onâ: Specific Templates
- Select templates in the âTemplatesâ dropdown
- 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:
- Select âLoad onâ: Custom Post IDs
- Enter comma-separated post IDs:
45, 67, 89 - 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
- Be specific: The narrower your conditions, the better
- Avoid âEverywhereâ: Unless absolutely necessary
- Test in builder: Conditions work in builder mode too
- Combine with caching: Long cache + specific pages = optimal
- 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:
- Verify your credentials in the API provider dashboard
- For bearer tokens, ensure you copied the complete token
- Check if your token has expired (regenerate if needed)
- Try different authentication methods if unsupported
- For dynamic tokens, verify token endpoint URL is correct
- 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:
- Check the URL in your browser - does it return JSON?
- Look at response headers - is Content-Type application/json?
- For XML APIs, the system auto-detects XML (no action needed)
- For CSV APIs, ensure Content-Type is text/csv
- Verify the API is operational
- 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:
- Verify fallback values are set for builder/testing
- Check the actual page URL includes the parameter:
?id=123 - Ensure parameter name matches exactly (case-sensitive)
- For Bricks tags
{post_id}, verify the post has that field - 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:
- Verify unique ID field: Ensure itâs selected and always present
- Check API response: Fetch data and verify the field exists
- Test uniqueness: Ensure no two items share the same ID
- Increase timeout: Add to
wp-config.php:set_time_limit(300); // 5 minutes - Increase memory: Add to
wp-config.php:define('WP_MEMORY_LIMIT', '256M'); - Check error logs: Look in WordPress debug.log for specific errors
- Sync smaller batches: Use conditions to sync fewer items first
- 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:
- Enable âCreate dynamic data tags automaticallyâ
- Click âFetchâ to load API data
- Set status to âActiveâ
- Save your configuration
- Clear cache: âClear Cacheâ button
- Refresh Bricks Builder (hard refresh: Ctrl+F5)
- 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:
- Click âClear Cacheâ for this API
- For CPT synced data, click âSync Nowâ
- Clear all WordPress caches (if using cache plugin)
- Clear object cache if using Redis/Memcached
- Purge CDN cache if applicable
- Check cache lifetime setting (maybe itâs too long)
- 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:
- Fetch API data first (click âFetchâ)
- Look for âSelect Nested Arraysâ section
- Check the boxes for nested arrays you want
- Click âSaveâ
- Refresh Bricks Builder
- 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:
- Make your sheet public or get a share link
- Use the Google Sheets API URL format:
https://sheets.googleapis.com/v4/spreadsheets/SHEET_ID/values/RANGE?key=API_KEY - First row = headers (automatically mapped)
- 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/xmlorapplication/xml - Valid XML structure
Note: XML is converted to nested arrays automatically.
Support
If you encounter issues not covered in this documentation:
- Community forum: Reach out to other users
- Support ticket: Contact Bricksforge support
- 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.