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.

Specify endpoint and authentication info

(Assuming https://d9.site/ is your Drupal 9 site URL.

Make up the headers and payload data

Then we make the POST to create a new article:

Check the result:

Expect a 201 code if creation is successful.

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

(aka gilzero). I occasionally write about Software Development, Web Development, Machine Learning.