Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Joomla 5 rest api example code for content submission


Joomla 5 rest api example code for content submission


Below is a comprehensive example and explanation of how to submit content using Joomla 5 REST API, including practical PHP code examples illustrating how to create an article via the Joomla API. This will cover necessary preparations, request structure, authentication, and the data fields needed for content submission.

***

Joomla 5 REST API Overview for Content Submission

Joomla 5 leverages a RESTful API that enables content management programmatically by providing endpoints for common operations such as creating, updating, fetching, and deleting articles. Content submission typically involves sending a POST request to the articles endpoint with proper authentication and a JSON body containing the article data.

The core verbs used in the Joomla API with respect to articles are:

- POST: Create a new article
- PATCH: Update an existing article
- GET: Retrieve articles
- DELETE: Remove an article

For content submission, the most relevant method is POST.

Authentication

The Joomla REST API usually requires authentication via a token. This token is generated in Joomla typically through an API Token system under user settings, and must be included in API requests for security.

The token is passed in the HTTP header typically as:

http
Authorization: Bearer YOUR_API_TOKEN_HERE

Essential Fields for Article Creation

When submitting content, Joomla expects certain mandatory fields to be included. The four main fields for posting an article via the API are:

- `title`: The title of the article
- `articletext`: The body of the article, which Joomla intelligently separates into `introtext` and `fulltext` if it detects a readmore tag
- `catid`: The category ID in Joomla where the article belongs
- `language`: The language code, or `*` for all languages

Additional optional fields can include `state` (published status), `tags`, `featured`, `access` level, and more.

Example PHP Script to Submit Content Using Joomla 5 REST API

Below is an example PHP script using cURL to submit an article via Joomla 5 REST API to your Joomla site.

php
 "Sample Article Title",
    "articletext" => "This is the full content of the article. You can use  to separate introtext and fulltext.",
    "catid" => 2, // Change to appropriate category ID
    "language" => "*", // Asterisk means all languages
    "state" => 1, // 1 means published
    "alias" => "sample-article-title" // Optional: URL alias
];

// Convert data to JSON
$jsonData = json_encode($data);

// Initialize cURL session
$ch = curl_init($apiUrl);

// Set cURL options for POST request
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Authorization: Bearer ' . $apiToken
]);

// Execute the request
$response = curl_exec($ch);

// Check for errors
if(curl_errno($ch)){
    echo 'Request Error:' . curl_error($ch);
} else {
    // Output response from Joomla API
    echo 'Response from Joomla API:' . PHP_EOL;
    echo $response;
}

curl_close($ch);
?>

This script:

- Sets the Joomla REST API endpoint (`/content/articles`) where new articles are submitted.
- Sets the necessary authorization token in the headers.
- Prepares the article data fields as JSON.
- Sends a POST request to the Joomla API.
- Receives and outputs the response from the Joomla server, which typically includes the ID and details of the created article.

Explanation on `articletext` Field

The `articletext` field is special in Joomla's API. If it detects the WordPress-style or Joomla-style readmore tag `` within the content, it automatically splits the content into `introtext` (the portion before the tag) and `fulltext` (the portion after the tag). This makes it easier to manage featured snippets.

Example content body with readmore:

html
This is the introductory part of the article.

This is the remaining full article content.

Additional Optional Fields

You may also include other article attributes, such as:

- `state`: Integer; 1 for published, 0 for unpublished, -2 for trashed.
- `featured`: Boolean to mark an article as featured.
- `access`: Integer for user group access levels.
- `created_by`: Integer user ID of the creator.
- `tags`: Array or comma-separated tag IDs.

Using Command Line with cURL to Submit a Joomla Article

You can also post content via the command line using cURL:

bash
curl -X POST "https://yourjoomlasite.com/api/index.php/v1/content/articles" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_JOOMLA_API_TOKEN" \
-d '{
  "title": "Command-line Article",
  "articletext": "Content submitted via command line.",
  "catid": 2,
  "language": "*",
  "state": 1
}'

This is useful for quick testing or automation scripts outside PHP.

Handling the Response

A successful POST request to create an article returns JSON data including the created article ID, link, and other metadata.

Example JSON response:

json
{
  "id": 123,
  "title": "Sample Article Title",
  "alias": "sample-article-title",
  "catid": 2,
  "language": "*",
  "state": 1
}

Updating Articles with Joomla API

To update an existing article, use HTTP PATCH method with the article ID endpoint:

php
$articleId = 123;
$updateUrl = "https://yourjoomlasite.com/api/index.php/v1/content/articles/$articleId";

$updateData = [
    "title" => "Updated Article Title"
];

$ch = curl_init($updateUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PATCH");
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($updateData));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Authorization: Bearer ' . $apiToken
]);

$response = curl_exec($ch);
curl_close($ch);
echo $response;

Setting Up Joomla API Environment

- Make sure the Joomla API plugin is enabled.
- Generate an API token from your Joomla administrator user profile.
- Confirm that the appropriate ACL permissions are set, allowing the API user to create and manage articles.
- Ensure your Joomla site has HTTPS enabled if passing tokens in headers for security.

Example for Custom Fields Submission

Joomla Articles can have custom fields which also can be set via the API by including fields using their alias names.

Example:

php
$data = [
    "title" => "Article with Custom Field",
    "articletext" => "Here is an article with a custom field set.",
    "catid" => 2,
    "language" => "*",
    "customfield_temperature" => "23°C"
];

The key `customfield_temperature` corresponds to a custom field alias created in Joomla. This updates the custom field value during the submission.

Other Considerations

- The API rate limits and security settings should be considered for production use.
- Use HTTPS always to keep tokens secure.
- Validate input data to prevent injection.
- Localization and multilanguage support can be managed using the `language` field.
- Tags and other taxonomy may require separate API calls or properly formatted arrays.

***

The above demonstrates how to programmatically submit content articles to a Joomla 5 site via its REST API, including example code in PHP and cURL, explanation of required fields, authentication, and response handling with custom fields support. This integration facilitates content automation and external system synchronization with Joomla CMS.

All content submission is done through POST at the `/content/articles` endpoint with an authorization token header, with data sent as JSON including at least title, articletext, category ID, and language fields for a successful content submission.

References for further reading:

- Joomla 5 API content submission examples (community resources)
- Joomla API Token authentication method
- PHP cURL usage for REST APIs
- Joomla custom fields API usage

This provides a solid foundation to build Joomla 5 content submission capabilities into applications or scripts.