Overview

I had an opportunity to add content to Drupal using Python, so this is a memo of the process. I referenced the following article.

https://weimingchenzero.medium.com/use-python-to-call-drupal-9-core-restful-api-to-create-new-content-9f3fa8628ab4

Preparing Drupal

I set it up on Amazon Lightsail. The following article is a useful reference.

https://annai.co.jp/article/use-aws-lightsail

Modules

Install the following modules.

  • HTTP Basic Auth
  • JSON:API
  • RESTful Web Services
  • Serialization

Changing JSON:API Settings

Access the following page to change the settings.

</admin/config/services/jsonapi>

Python

Set {IP address or domain name} and {password} as appropriate.

For Amazon Lightsail, the default username is user. You can check the password with the following command.

cat ~/bitnami_application_password
import requests
from requests.auth import HTTPBasicAuth

endpoint = 'http://{IP address or domain name}/jsonapi/node/article'

u = 'user'
p = '{password}'

headers = {
    'Accept': 'application/vnd.api+json',
    'Content-Type': 'application/vnd.api+json'
}
payload = {
    "data": {
        "type": "node--article",
        "attributes": {
            "title": "What's up from Python",
            "body": {
                "value": "Be water. My friends.",
                "format": "plain_text"
            }
        }
    }
}

r = requests.post(endpoint, headers=headers, auth=(u, p), json=payload)
r.text

Additional Notes

I also attempted to register a node_type as follows.

payload = {
    "data": {
        "type": "node_type--node_type",
        "attributes": {
            "title": "テスト",
            "description": "node_typeのテストです。"
        }
    }
}

url = f"{host}/jsonapi/node_type/node_type"
r = requests.post(url, headers=headers, auth=(username, password), json=payload)
r.json()

As a result, I received a Method Not Allowed error as shown below.

{'jsonapi': {'version': '1.0',
  'meta': {'links': {'self': {'href': 'http://jsonapi.org/format/1.0/'}}}},
 'errors': [{'title': 'Method Not Allowed',
   'status': '405',
   'detail': 'No route found for "POST /jsonapi/node_type/node_type": Method Not Allowed (Allow: GET, HEAD)',
...

I plan to continue investigating this issue.

Summary

I will continue investigating in order to use Drupal as a headless CMS.