Use Python to call Drupal 9 core RESTful API to create new content
With Drupal 9 out-of-the-box RESTful support make decoupling so much more convenient. We make it Drupal 9 as a decoupled headless service, serving entities for external apps. (Python, Java, NodeJS whichever you favor)
Intro
In this post, I will show you how to use Python to make an API POST call to Drupal for creating new content. Use the article content type as an example, as the article node type is come by default.
Make sure you also read about the security reminder in Afterwords.
Let’s start:
The environment at the time of my writing
- Python 3.8
- Drupal 9.26
Enable Drupal 9 core Web Services related modules.
- HAL
- HTTP Basic Auth
- JSON:API
- RESTful Web Services
- Serialization
In this case, we will mainly use JSON:API.
Go to the configure page:
https://example.com/admin/config/services/jsonapi
Select the option and Save.
Accept all JSON:API create, read, update, and delete operations.
Create a Python file, drupal.py
Use requests module and Basic Auth.
import requests
from requests.auth import HTTPBasicAuth
Specify endpoint and authentication info
(Assuming https://d9.site/ is your Drupal 9 site URL.
endpoint = 'https://d9.site/jsonapi/node/article'
u = 'username'
p = 'password'
Make up the headers and payload data
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"
}
}
}
}
Then we make the POST to create a new article:
r = requests.post(endpoint, headers=headers, auth=(u, p), json=payload)
Check the result:
Expect a 201 code if creation is successful.
print(r.headers)
print(r.status_code)
print(r.json())
Afterwords
About Security
This is a demo example to illustrate the communication of the Drupal 9 core REST API with Python.
Please note that we use the Basic Auth method to verify the user.
The username and password are hard-coded in the script.
Basic Auth is simple and literally ‘basic’, if you decide to use Basic Auth, make sure at least the site is under HTTPS, has a valid SSL/TLS certificate.
Otherwise, your credentials might be intercepted during transmission, remind that your script code is secure with appropriate read permission
In addition, to take good practice to Drupal, you might also consider creating a specific user and set that account of a certain role with permissions for a single purpose.
For production and or more sensitive data to POST, consider using OAuth 2.
Happy calling. :)
Python + Drupal