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

Does Craft CMS Have An API?

10 min read
Shape April 2022 HR 201

Wondering if Craft CMS offers developer APIs to build custom solutions? As Craft continues to grow in popularity, its comprehensive API capabilities are a huge selling point. This post dives into what Craft's API offers, its key benefits for developers, and how to leverage it for headless, plugins, automation and more. Read on to learn if Craft's API can supercharge your next project.

Yes, Craft CMS has a comprehensive REST API with 60+ endpoints to access all core content models. It enables building plugins, headless sites, integrations, and custom apps. The API is well documented with extensive resources to support developers. Over 300 plugins leverage the API to extend Craft's capabilities.

Craft CMS API

Overview of the Craft CMS API

The Craft CMS API allows developers to interact with Craft CMS programmatically. An API (Application Programming Interface) is a set of protocols and tools for building software applications. The Craft API provides a way for developers to connect their code to a Craft CMS install in order to exchange data and trigger actions.

With the Craft API, developers can build plugins, integrations and applications that can pull data from Craft or push data into Craft. It enables developing custom functionality, building headless setups where Craft acts as a backend content repository, and integrating Craft with external platforms and services.

The API exposes various endpoints that allow access to different sections of Craft, like Entries, Categories, Users etc. Developers authenticate with the API using an API key and can then make requests to read, write, update and delete content through the endpoints.

Overall, the API opens up many possibilities for developers to extend Craft CMS or build apps powered by the content in their Craft installs. It's a powerful tool that forms the backbone of the Craft ecosystem.

Purpose and Benefits of the API

The main goal of the Craft API is to enable developers to integrate Craft CMS with other apps and systems. It aims to provide a simple yet robust way for developers to tap into their Craft datasets and leverage the content management capabilities of Craft.

Some of the key benefits unlocked by the API include:

  • Headless CMS - The API allows Craft to be used as a headless CMS that acts solely as a backend content repository while a separate frontend app pulls that content.

  • Custom Integrations - Developers can build one-off integrations between Craft and other tools like CRMs, e-commerce platforms etc. This expands Craft's capabilities.

  • Plugin Development - The API enables the development of custom Craft CMS plugins that add new features, automations and enhancements.

  • Mobile Apps - Craft content can be made available in mobile apps by having the apps connect to the API. This brings content to new channels.

  • Extending Craft - Developers can use the API to extend Craft's base feature set for specific use cases like multi-site management.

  • Automation - Syncing content out to other systems or automating tasks can be achieved using the API.

So in summary, the API opens up Craft CMS so that developers can build on top of it in nearly limitless ways, according to their specific needs. This extensibility provides great value.

Documentation and Resources

The Craft API has extensive documentation available online that provides a comprehensive reference for working with all aspects of the API. The documentation covers core topics like authentication, endpoints, payload formatting, error handling as well as docs for each individual endpoint.

Some helpful resources include:

  • Official Craft CMS API documentation - The complete API reference from Craft themselves.

  • Craft CMS Stack Exchange - A Q&A site where developers can ask API related questions.

  • Straight Up Craft Slack - An active Slack community of Craft developers with #api channel.

  • Plugin documentation - Plugins like CraftQL and Craft-Scripts utilize the API extensively and provide guidance.

  • Blog posts - There are many tutorial style blog articles on using the Craft API for common tasks.

  • Courses - Platforms like Mammoth provide Craft API training courses for different levels.

  • Craft Developer Discord - Discord channel focused on Craft development and APIs.

Between the extensive official documentation and additional learning resources, developers have many options to gain proficiency with the Craft CMS API. Support is also available through the Craft community in places like Stack Exchange forums. Overall, it is a well documented API that empowers developers to tap into the power of Craft CMS.

Authentication and Accessing the API

API Keys and Setup

To start using the Craft CMS API, you first need to generate an API key. This can be done from the Settings section in the Craft control panel. Under the Users tab, choose a user account and enable the "Allow this user to make API requests?" option. An API key will be generated that serves as the authentication credential.

It's recommended to create a dedicated user account just for API access, with appropriate permissions granted. Don't use admin accounts for the API if possible. Also generate separate

API keys for each app or integration, for more targeted access control.

When making API requests, the key should be passed in the request header like:

Authorization: Bearer {API_KEY}

Keys can be regenerated if compromised and expired keys will return authorization errors. It's good practice to periodically cycle API keys and not rely on single static keys.

Overall, with a simple API key generation process and passing the key in requests, the Craft API provides a straightforward yet secure authentication mechanism.

User Permissions and Scopes

The API permissions for a key correspond to the control panel permissions of the user account it is associated with. So an API key for an admin user would have full API access, while keys for less privileged users may have restrictions.

Certain user groups can be defined that have granular permissions for specific sections, entry types, fields etc. By generating API keys linked to those groups, access can be narrowed to just what's needed for that integration.

For example, a "Blog API" group could be set up with read-only access to blog sections and entries. An API key tied to a user in that group would then be restricted to only fetch blog content.

Scopes provide another way to lock down API keys, like limiting them to a single endpoint. Overall, the Craft API has multiple levers to tailor permissions according to each use case.

Security Considerations

Since the API provides extensive access to Craft installs, it's important to follow security best practices when working with the API:

  • Use SSL/HTTPS encryption for all API traffic to protect from eavesdropping.

  • Validate all payloads on the server before processing to guard against malicious requests.

  • Enforce strict rate limiting to prevent brute force attacks and abuse.

  • Restrict API keys to be from specific IP addresses if feasible as an extra safeguard.

  • Use short expiration times for transient keys that only need temporary access.

  • Follow least privilege principles when assigning user/group permissions tied to keys.

  • Revoke compromised API keys immediately if any issues arise.

  • Keep the Craft install and all plugins/modules updated to the latest versions.

  • Enable Craft's built-in password security policies and other protection tools.

  • Employ proper DevOps processes like code reviews, testing, auditing when building with the API.

By implementing reasonable security practices around API key handling, configuration, development, and operations, the risks associated with opening Craft's data via an API can be minimized. The official Craft CMS documentation provides additional best practices for securing the API. With the proper precautions, the API can be safely leveraged for many useful integrations and applications.

Core Endpoints and Requests

Entries, Categories, Assets, and More

The Craft API exposes endpoints for all the core content models including:

  • Entries - Get, create, update, delete entries in sections.

  • Categories - Manage categories that structure content.

  • Assets - Upload, manage, manipulate assets like images.

  • Tags - Manage tags applied across content.

  • Users - Create, manage, assign roles to editor users.

  • Globals - Read and write global content fields.

  • Fields - Get field definitions and configure settings.

For example, to get a list of blog entries:

GET /entries?section=blog

To create a new category:

Copy code

POST /categories

{

"group": "blogCategories",

"title": "New Category"

}

The endpoints provide access to manipulate all of Craft's core content models.

CRUD Operations

The API supports full CRUD (Create, Read, Update, Delete) operations for content via common HTTP methods:

  • GET - Retrieve one or more resources

  • POST - Create a new resource

  • PUT/PATCH - Update an existing resource

  • DELETE - Delete a resource

For example:

GET /entries - get list of entries

GET /entries/123 - get one entry


POST /entries - create new entry


PUT /entries/123 - update entry


DELETE /entries/123 - delete entry

These core REST-like CRUD principles make the Craft API easy to work with for developers familiar with web APIs.

Parameters, Pagination, and Filtering

The API accepts various parameters to tailor requests:

  • limit - Limit number of resources returned

  • offset - Offset start of resources returned

  • search - Search query to filter responses

  • relatedTo - Eager load related elements

  • orderBy - Sort response by a field

Pagination can be implemented using limit and offset. search filters based on keywords. relatedTo efficiently loads relational data.

For example:

GET /entries?limit=10&offset=20 - Get 10 entries starting from 20

GET /entries?search=foo - Get entries matching "foo"

GET /entries?relatedTo=category:1 - Fetch entries related to Category ID 1

Overall, the flexible parameters provide many options for tailoring API requests and responses.

Working with Content

Fetching and Reading Content

The API provides several ways to fetch and read content from a Craft install. Simple GET requests to endpoints like /entries or /categories will return the lists of those elements.

For example:

GET /entries - Get all entries

GET /entries?limit=10 - Get 10 entries

GET /entries/123 - Get entry with ID 123

Parameters like limit, offset, search, orderBy can be used to paginate or filter the results.

Related or relational data can be eager loaded using the relatedTo parameter to minimize requests:

GET /entries?relatedTo=author:12 - Fetch entries related to Author 12

Error handling is important when consuming APIs. The Craft API returns understandable errors like:

{

"error": "Invalid credentials"

}

Overall, fetching and reading content via the API is straightforward with the flexible options to tailor returned results.

Modifying Content

To create, update or delete content, the POST, PUT/PATCH, and DELETE methods can be used.

For example, to create a new entry:

POST /entries

{

"section": "blog",

"title": "My New Post",

"slug": "my-new-post",

"body": "Hello World!"

}

To update an existing entry:


PATCH /entries/123

{

"title": "Updated Post Title"

}


Deleting content:

DELETE /entries/123

The API enables a full range of CRUD operations for crafting dynamic experiences and workflows.

Uploading Assets

Assets like images can be uploaded directly to Craft via the API by sending a multi-part POST request:

POST /assets

- Form field: enabled=true

- File field: imageToUpload

The enabled flag publishes the asset. Custom fields can be populated too.

Existing assets can also be manipulated:

PUT /assets/123

{

"title": "New image title"

}

This allows uploading images from apps directly into Craft asset volumes. The same process applies for uploading files as well.

Overall, the API provides comprehensive tools for managing all types of content and assets within Craft CMS.

Extending Craft with Plugins

Developing Plugins

The Craft API enables developers to build custom plugins that integrate tightly with Craft. Plugins are self-contained code packages that add functionality.

They can interact with Craft content, data models, business logic and UI through API requests.

For example, a plugin could:

  • Fetch latest entries via the API and display them

  • React to entry updates by triggering workflows

  • Expose REST APIs for mobile apps

  • Create custom UI elements and admin settings

Plugins are written in PHP and can leverage dependencies like Guzzle for API requests:

// Fetch client instance

$client = Craft::$app->getApi();


// Get entries

$response = $client->getEntries([

'section' => 'blog'

]);


// Display titles

foreach ($response->getEntries() as $entry) {

echo $entry->title;

}

Overall, plugins enable extending Craft in unlimited ways by tapping into the same APIs available externally.

Exposing Custom Endpoints

Plugins can expose custom APIs and endpoints by adding controllers. This allows creating new routes and integrating with external services.

For example, a controller could handle webhook requests from a third party:

class WebhookController extends Controller

{

public function actionReceive()

{

// Handle webhook request

$orderId = Craft::$app->getRequest()->getRequiredBodyParam('orderId');

// Lookup order in Craft via API

$order = Craft::$app->getOrders()->getOrderById($orderId);


// Do something with order

// (...)


return $this->asJson(['success' => true]);

}


}

Controllers greatly expand the flexibility of the Craft platform.

Modifying Front-end Components

For frontend JavaScript apps that need Craft data, plugins can inject custom editable React, Vue and other components that call the API.

For example:

// Feed.vue


export default {

// Fetch entries via API

async created() {

const response = await fetch('/actions/plugin/entries');

this.entries = await response.json();

},


template: `

<div>

<div v-for="entry in entries">

{{ entry.title }}

</div>

</div>

`

}

This allows populating dynamic frontend experiences. The same approach applies for React, Angular etc.

Overall, the Craft CMS API enables creating versatile plugins that customize Craft in infinite ways.

Example Projects and Use Cases

Headless with Next, React, Vue

The Craft API excels at powering headless CMS implementations with modern JavaScript frameworks like Next, React, and Vue.

For example, Next.js can leverage the API to fetch pages and posts from Craft:


// pages/[slug].js


export async function getStaticProps({ params }) {


const response = await fetch(`https://mycraftcms/entries/${params.slug}`);

const entry = await response.json();


return {

props: {

entry

}

}


}


export default function Page({ entry }) {

return <h1>{ entry.title }</h1>;

}


The same works for fetching categories, authors etc. This decouples the frontend from the CMS while still leveraging Craft's editing experience.


Similar integrations are possible with React by fetching API data in effects and hooks. Vue can query the API in lifecycle methods to populate components.

Mobile and Desktop Apps

Native mobile apps provide another avenue for tapping into Craft via the API. A reactive SwiftUI app could integrate with Craft content as follows:


// Fetch entries

@ObservedObject var entries: [Entry] = []


init() {

let url = URL(string: "https://mycraftcms/entries")!

URLSession.shared.dataTask(with: url) { (data, _, _) in

let entries = try! JSONDecoder().decode([Entry].self, from: data!)

DispatchQueue.main.async {

self.entries = entries

}

}.resume()


}


Similarly, cross-platform solutions like React Native or Flutter paired with the API enable Crafty mobile apps on iOS and Android.


For desktop, Electron apps can connect to Craft to enable capabilities like customized editing interfaces.

Sample Plugins and Projects

Many open source Craft plugins and projects demonstrate using the API:

The Straight Up Craft blog also covers many API tutorials. Additional code samples are on GitHub under the craftcms organization.

There is no shortage of inspiring projects and resources for getting started with the Craft CMS API.

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