We use cookies to make your viewing experience better. By accepting you consent, you agree to our Cookie policy

Accept
Improve your Craft CMS skills

A User Guide For The Craft CMS Element API Plugin

10 min read
Craft CMS Element API

The Craft CMS Element API plugin unlocks powerful API capabilities for accessing Craft content and functionality. This guide covers everything needed to leverage the robust CRUD operations, advanced queries, and flexible configurations to integrate Craft seamlessly with external systems and applications. Follow along to master using the Element API for building headless Craft implementations, smooth frontend integrations, and optimized content workflows.

The Craft CMS Element API plugin enables full CRUD operations, advanced queries, and flexible configuration to integrate Craft with external systems. It allows managing entries, assets, users, and data through a JSON REST API with endpoint authentication, access control, caching, webhooks, CORS support, and robust relational/element querying.

Getting Started

Downloading and Installing

The Element API plugin provides a simple way to access and manipulate elements in Craft CMS through a JSON API. To get started with it, you first need to download and install it.

The plugin can be downloaded from the official Craft plugin store or from GitHub. The GitHub repository contains the development version which may have the latest features but also bugs. The plugin store has the latest stable release which is recommended for most users.

Once downloaded, installing the plugin is straightforward. Go to Settings > Plugins in your Craft control panel and upload the zip file. The only requirements are a minimum PHP version of 7.0 and Craft CMS 3.1+.

After uploading, Craft will extract the files and you can click "Install" to activate the plugin. That's it - the plugin will now be installed and enabled on your site! No further steps are required.

Some key points for installing the Element API plugin:

  • Download from plugin store or GitHub

  • Upload and install just like any Craft plugin

  • Requires PHP 7.0+ and Craft CMS 3.1+

  • No special configuration needed for installation

  • Enabled automatically after installing

With those simple steps, you'll have the powerful Element API plugin ready to use on your Craft site.

Initial Configuration

After installing the Element API plugin, some initial configuration may be required depending on your use cases. The plugin works out of the box with its default settings but can be customized as needed.

Under the plugin's settings, the first option allows specifying which Craft API endpoints should be accessible. By default, all endpoints are enabled but you may want to restrict access. Unchecking an endpoint disables the related API calls.

Next is access control for the API. Here you can limit API access to specific user groups. This lets you restrict the API to only authorized users. The default option allows access for all user groups.

Authentication for the API can also be configured. By default, a user needs to be logged into the Craft control panel to use the API. Optional basic HTTP authentication can be enabled which allows sending an access token with the API requests.

Some other configuration options include:

  • Specifying a custom API endpoint prefix

  • Adding CORS headers for cross-origin requests

  • Logging requests and errors

  • Caching responses

Key things to understand about the initial setup:

  • Default options work for simple use cases

  • Lock down API access and endpoints if needed

  • Enable HTTP authentication for token-based API access

  • Tweak settings like CORS and caching based on frontend

With those configuration options, the Element API plugin can be tailored to your specific API requirements. Just a few tweaks to enable a fast, secure and custom API for your Craft site.

Key Features

CRUD Operations

The Element API plugin provides comprehensive create, read, update, and delete (CRUD) operations for Craft elements. This enables programmatically managing elements through the API in any way needed. The create function allows generating new elements like entries, categories or assets by setting all field values through the API request.


Reading elements is handled through API endpoints that return JSON data for one or more elements filtered by criteria. Fetching a single element or getting all entries of a type can be done simply. Updating existing elements is possible by sending updated properties via a PATCH request, with the ability to selectively update individual fields without affecting the rest of the element.

Finally, deleting elements can be done by passing the element ID or query parameters to permanently delete all matched elements. In summary, the full CRUD capabilities empower creating, reading, updating, and deleting elements via the API.

Advanced Queries

The Element API plugin provides robust advanced querying capabilities when reading elements. Craft's extremely flexible querying engine is available in full through the API. Complex criteria with AND/OR conditions, sorting, limit parameters, and more can be passed in to filter elements in specific ways. Search parameters can contain complex search strings using Craft's syntax.

Relational queries make it easy to fetch related elements and assets in the same call, with deep relational queries possible for nested structures. Some custom parameters add further functionality, like returning only field values without full elements, disabling lazy-loading of elements, or getting the total matched element count.

In essence, advanced API queries allow leveraging the full power of Craft's element querying to filter and relate data in complex ways when reading elements.

Modifying Structures and Relations

A major benefit of the Element API is the ability to modify and manage structural elements and inter-element relations. The API enables creating Craft CMS categories, updating, and deleting entries and categories within sections and structures. It can reshape content by moving elements between categories, sections, etc.


Relations from entries to assets, users and tags can be created, updated and deleted as well. Asset relations between folders and subfolders are also manageable through the API. Some examples include creating and deleting categories, moving entries between structures, attaching and removing related assets from entries, renaming asset folders, and moving assets between folders.

In summary, the Element API plugin empowers developers to completely manage structures and relations between elements through API calls.

Fetching Elements

Endpoints and Requests

The Element API plugin provides several endpoints for fetching elements based on different parameters. Understanding the endpoints and request formatting is key to retrieving elements.

The /elements endpoint returns multiple elements by element type or other query criteria. Passing an element ID to /elements/{id} will return just that single element.

Requests are made as JSON APIs with typical methods like GET, POST, PATCH and DELETE. GET requests allow fetching elements while POST creates new ones.

Some examples of API requests:

  • GET /elements?type=entries

  • GET /elements/123

  • POST /elements
    • with JSON body containing new element data

The plugin follows REST API conventions so the endpoints and requests will be familiar to API developers.

Key points about element API requests:

  • Use endpoint paths like /elements and /elements/{id}

  • GET returns and POST creates

  • Pass element types, IDs and other query parameters

  • Requests formatted as JSON APIs

With well structured endpoints and JSON formatted requests, the Element API makes fetching Craft elements simple.

Query Parameters

The Element API allows passing many query string parameters to filter, sort, limit and customize the element results returned.

Some supported parameters include:

  • search - Search query to filter elements

  • type - Element type like entries or categories

  • limit - Limits the number of elements returned

  • offset - For pagination, skips a number of elements

  • orderBy - Field to sort by

  • with - Eager loads related elements


These query options allow retrieving exactly the elements needed from the vast possibilities in Craft CMS. Chaining together parameters filters down the results at multiple levels.

Some examples:

  • /elements?limit=10 - Get 10 elements

  • /elements?type=entries&search=foo - Get entry results matching "foo"

  • /elements?with=relatedArticles - Eager load related articles

The flexibility helps minimize requests and data transfer for optimal Element API usage.

Pagination and Response Formats

When fetching a large number of elements, the API endpoints support Craft CMS pagination using the limit and offset parameters.

The response provides headers like X-Total-Count for the total available elements to calculate further pages. JSON responses contain the elements and any eager loaded related elements.

For errors, JSON responses include readable error messages and status codes follow API standards like 400 for invalid requests and 500 for internal errors.

The Element API plugin provides well formatted JSON element responses out of the box, while also allowing customizing the serialization through plugins like Custom Fields.

Creating Elements

Endpoints

The Element API plugin enables programmatically creating new elements through a simple POST request to the /elements endpoint with a JSON body containing the element data. This will return the newly created element's ID. Required fields for basic creation include the element type, enabled status, and title.

The Content Model fields can also be passed in the body to populate the new element with data on creation. By default, Craft's native validation rules are enforced when creating elements via the API so invalid data will return errors. In summary, the /elements endpoint allows creating any element type just by passing the type, title, enabled status, and other Content Model fields in the POST request.

Supported Element Types

The API endpoint supports creating all of Craft's built-in and custom element types like entries, categories, assets, users, and more. For example, new blog entries can be created by passing the section, title, and content fields.

Products can be generated by providing the SKU, price, images, and other catalog fields. Users and customer accounts can be created by passing name, email, password, and custom user fields. Even complex nested elements can be created in a single call by populating the relational field data.

The API handles any element Craft can handle. Common uses cases include creating blog posts and articles, catalog products, assets like images and videos, categories and structures, user accounts, and tags for taxonomies. In essence, the endpoint allows effortlessly creating any element type dynamically through the API.

Additional Settings

Some additional parameters can be passed when creating elements to provide more control over the creation process. These include setting statuses, custom slugs, post dates, and initial custom field values.

For example, slugs can be auto-generated or set to a predefined custom value for URLs. Entry statuses like "live" or "pending" can be set along with post dates. Initial values for custom fields help prepopulate elements with data on creation.

An id parameter can also be passed to ensure idempotency if creating duplicate elements. In summary, the API provides flexibility to initialize elements with statuses, dates, slugs, field values, and other settings while creating them on the fly.

Updating Elements

Update Endpoint

The Element API allows updating existing elements through PATCH requests to the /elements/{id} endpoint, where the ID in the path targets the specific element to update.

The JSON body contains only the changed properties to enable partial updates. This avoids needing to pass the entire element just to change a few fields. Full revision history is maintained as updates create new revisions while previous versions remain available. Only metadata like titles and slugs can be modified on old non-current revisions.

In summary, the /elements/{id} PATCH endpoint enables precisely controlling updates on specific elements by passing just the changed properties. Revisions are fully maintained and non-current drafts can only be changed in limited ways.

Changing Properties

The update endpoint supports modifying any element property like titles, slugs, authors, statuses, entry types, and custom fields.

For example, entry titles and slugs can be changed to refresh content. Category names and authors can be updated to keep structures organized. Asset filenames and focal points can be tweaked to perfect media. Entries can be switched between draft and live status for publishing.

Even complex relational properties between elements can be changed. Updates cascade and modify related elements automatically - changing an entry slug will update any related URLs pointing to that entry. In essence, the API enables updating titles, slugs, authors, statuses, fields, relations, and any other element properties needed.

Version Handling

The Element API gracefully handles updates across different versions and statuses. Trying to update a non-existent element returns a clear 404 error, while invalid update requests return 400 errors.

Updating old non-current revisions will only change the metadata but not propagate to live until the revision is saved, enabling safe draft editing. Changes are synced automatically between current drafts and live versions - updating one will update the other.

In summary, robust version handling ensures updates behave predictably across all element versions, avoiding errors through clear messaging, allowing draft changes without impact, and syncing changes between live and draft versions.

Deleting Elements

Deletion Endpoints

The Element API provides endpoints for both permanently deleting elements via DELETE /elements/{id} and soft deleting with DELETE /elements/{id}/trashed. The former completely removes the element and its revisions while the latter trashes it while retaining revisions.

Batch deletion is also possible by passing element queries instead of IDs. In summary, the RESTful delete endpoints enable precisely controlling whether elements are soft or permanently hard deleted individually or in bulk.

Cascading Deletions

When deleting elements, related elements can also be removed cascadingly. For example, deleting a category could also delete all its child entries, while removing an asset folder cascades to delete its subfolders and assets as well.

This behaviour depends on the "Delete descendants" setting which can respect soft deletion rules or be forced to hard delete relations. Useful cases include deleting a category plus its entries, removing an asset folder and its contents, and forcibly cascading hard deletions through relations.

In essence, cascading deletions help maintain structural integrity by cleaning up associated elements upon deletion.

Error Handling

Some common errors that can occur when deleting elements include 404 "Not Found" when trying to delete non-existent elements, 403 "Forbidden" for permission errors if the API key lacks deletion rights, and various 400-level errors for invalid requests and endpoint usage.

Appropriately handling these predictable errors through try/catch allows robust deletion handling. Key scenarios are missing element 404 errors, insufficient permission 403 errors, and invalid request 4XX errors. In summary, appropriate error reporting and handling ensures the Element API deletion endpoints behave as expected.

Managing Relations

Endpoints

The Element API provides endpoints for fetching and modifying relational data. Related elements can be fetched through the /elements and /elements/{id} endpoints using the with parameter. Updating relations is handled by the /elements/{id} PATCH endpoint by passing the new related element IDs in the request body. For example, an entry can be fetched with its related categories, and then those categories can be updated by sending the new IDs.

Products can be retrieved along with their variant elements, and new variants can be related to the product. In summary, the core endpoints enable both reading related element data and managing relational connections between elements.

Hierarchies and Structures

The API supports modifying hierarchical structures between elements by creating, assigning, reordering, duplicating etc. New categories can be created and assigned to entries, with full control over the structure. Product variants can be added, managed, and ordered.

Changes properly cascade across structures - moving an entry to a new category automatically updates other related elements. Some specific examples are reordering and nesting categories, adding/removing product variants, and duplicating entire structures.

The key capabilities include creating, reordering, and removing relational connections, coupled with the ability to fully manage complex hierarchies and structures between elements.

Examples

Some common examples include managing relations between entries and categories, products and variants, assets and folders, users and groups.

For entries and categories, this includes fetching entries with related categories, assigning and unassigning categories, creating new categories and relating them, plus reordering and nesting categories.

For products and variants, it involves retrieving products with variants, adding new variants, modifying variant properties, and enabling/disabling variants.

For assets in folders, use cases involve getting folder structures, moving assets between folders, and creating/deleting folders.


Finally, for users and groups, examples include getting user groups with assigned users, assigning users to new groups, and removing user group relations. The API supports these and many other complex relational scenarios.

Advanced Queries

Query Options

The Element API provides robust options for complex querying beyond basic fetching. Powerful features include relational queries to eager load related elements, custom parameters like status and version to filter results, complex conditional filtering using AND/OR logic, subqueries for nested relations, and advanced control over sorting and pagination.

This enables tailored queries like fetching entries with their related assets and categories, getting only enabled elements or specific statuses, applying conditional rules like price > 100 AND stock < 10, and paginating large result sets 100 per page sorted by date created. The advanced options help minimize requests by enabling powerful filtering, sorting, relating, and pagination.

Criteria and Filters

The API supports advanced criteria-based queries using a filter syntax. Filters allow specifying field conditions like title='Foo', complex nested rules with AND/OR logic, operators like >=, *=, IN(), etc, and querying across multiple element types in the same call.

Some examples are status = 'live' AND (authorId = 5 OR authorId = 8), price >= 100 AND (categoryId IN (2,3) OR tags contains 'foo'), and type = 'entries' OR type = 'products'. This provides complete flexibility to filter, relate and query elements in any way needed.

Performance Considerations

Some performance considerations for complex queries include using indexed custom fields for filterable columns, enabling caching of common queries, keeping eager-loaded relations shallow to avoid N+1 queries, and paginating large result sets for quicker responses.

Other tips are avoiding expensive uncached queries in loops, limiting fields returned with the fields parameter, and testing query performance with logging and headers.

The key takeaways are indexing custom fields, caching common queries, eager loading relations judiciously, and paginating large results sets can help optimize advanced queries.

Templating and Output

Twig Integration

The Element API plugin natively integrates with Twig templating to output API data on the frontend of Craft sites. Twig tags like craft.api.elements enable making API requests directly within templates, with the response data outputtable immediately.

For example, entries can be fetched and looped through to output titles and URLs. Twig filters like api() pass template variables into API endpoints as parameters for easy integration. For example, an existing entry model can be passed to get its API representation.

In summary, native Craft CMS Twig filters and tags provide straightforward integration to output API responses in templates.

Code Samples

Some common code samples include fetching recent blog posts by limiting entry API requests, outputting an entry's categories by passing the entry to the categories endpoint, and listing commerce products by querying product elements. Recent posts can be displayed by getting the 10 latest blog entries, limited by section and count.

Entry categories can be output by passing the entry to api('categories') to get the related categories. Products can be listed by fetching commerce product elements and outputting titles and prices. The seamless Twig integration allows querying and outputting API data using minimal templating code.

Optimization and Security

Some optimization and security considerations involve caching API requests to avoid re-fetching, limiting sensitive fields returned, using rate limiting to prevent abuse, and being careful not to expose API keys on the front end.

Additional tips are minimizing element queries for better performance, disabling unneeded API endpoints, and using HTTP authorization instead of API keys in templates. The core goals are caching API requests, restricting exposed fields, implementing rate limiting to prevent abuse, and avoiding leaking credentials into templates. This ensures optimal and secure use of the Element API in frontend templates.

Plugin Configuration

Authentication and Access

The Element API plugin provides configuration options for authentication, access control, and security. Authentication can be required through control panel user logins or token-based HTTP authentication for front-end clients.

Access control settings enable limiting API access to only certain approved user groups, while private API requests can be scoped to the current logged-in user. For public access, anonymous unauthenticated usage can be allowed if needed.

The key capabilities are requiring a control panel or token-based login, restricting API access to authorized user groups, and allowing public anonymous access. Fine-grained configuration ensures the API is secured as needed for specific use cases.

Caching and Performance

Performance-related settings help optimize the Element API. Caching options include caching requests by URL, headers, and parameters to avoid duplicate API calls, with configurable cache lifetime.

Rate limiting allows restricting requests per minute and hour along with whitelisting IP addresses. Indexing ensures custom fields used for filtering have indexes for performant lookups. Enabling these features helps minimize load for public-facing APIs. Additional useful settings are controlling caching granularity, setting specific rate limits, ensuring custom fields are indexed, and disabling unneeded API endpoints. Optimized configuration delivers speedy API performance.

Additional Settings

Some other helpful plugin settings include enabling CORS for cross-origin requests, debug mode to log all requests, webhooks for external notifications, and customizable events for extending functionality.

Miscellaneous configurations include customizing the endpoint path prefix, controlling response formatting, and flexible logging options.

In summary, the additional settings provide well-rounded configuration including CORS support, debug logging, webhooks and events for extensibility, and miscellaneous customizations for prefixes, formatting, and logging.

Shape April 2022 HR 202
Andy Golpys
- Author

Andy has scaled multiple businesses and is a big believer in Craft CMS as a tool that benefits both Designer, Developer and Client. 

Share
Feedback
Show us some love
Email Us
We usually reply within 72 hours
Agency Directory
Submit your agency
Affiliate Partners
Let's chat