Using curl to query Drupal 8 web service

By xngo on February 21, 2019

Enable web service

In Drupal 8, to enable web service, go to Manage > Extend page and enable the following modules:

  • HAL
  • HTTP Basic Authentication
  • JSON:API
  • RESTful Web Services
  • Serialization

Navigate to Configuration > JSON:API and then check Accept all JSON:API create, read, update, and delete operations.

Create an article

The shell script below will use cURL to create an article. Make sure that you change the followings to match your case:

  • The domain name => http://example.com
  • The username and password => admin:x
CONTENT='{
            "_links": {
                "type": {
                    "href": "http://example.com/rest/type/node/article"
                }
            },
            "title": [
                {
                    "value": "Example node title"
                }
            ],
            "body": [
                {
                    "value": "This is the body content of my page",
                    "lang": "en"
                }
            ],            
            "type": [
                {
                    "target_id": "article"
                }
            ]
        }'
 
curl --user admin:x --request POST \
      --header 'Content-type: application/hal+json' \
      http://example.com/entity/node?_format=hal_json \
      --data-binary "${CONTENT}"
 
# If the node is created successfully, 
#   then curl will return the whole JSON of the node created.

Retrieve an article

# Change the followings to match your Drupal setup:
#   http://example.com/
#   Username and password => admin:x
#   The node ID your want to fetch => node/1
curl --user admin:x --header 'Accept: application/hal+json' \
        --request GET http://example.com/node/1?_format=hal_json

Github

  • https://github.com/xuanngo2001/drupal-webservice/tree/master/node

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.