Overview
In the following article, I described how to create new content.
This time, I’ll try updating and deleting existing content.
Filtering Items
With the following program, you can retrieve registered content. This time, I retrieved content with the title “Pre-update title.” res["data"] is an array.
username = "xxx"
password = "xxx"
host = "xxx"
query = {
"title": "更新前のタイトル"
}
item_type = "article"
filters = []
for key, value in query.items():
filters.append(f'filter[{key}]={value}')
filter_str = '&'.join(filters)
endpoint = f'{host}/jsonapi/node/{item_type}?{filter_str}'
r = requests.get(endpoint, headers=headers, auth=(username, password))
res = r.json()
len(res['data'])
Getting the ID of the Content to Update
An ID like 730f844d-b476-4485-8957-c33fccb7f8ac is obtained.
item = res['data'][0]
item_id = item['id']
Updating
Specify the type and id to update.
payload = {
"data": {
"type": f"node--{item_type}",
"id": item_id,
"attributes": {
"title": "更新後のタイトル"
}
}
}
url = f"{host}/jsonapi/node/{item_type}/{item_id}"
r = requests.patch(url, headers=headers, auth=(username, password), json=payload)
r.json()
Deleting
Deletion can be executed as follows.
requests.delete(url, auth=(username, password))
Summary
I hope this serves as a useful reference when editing content on Drupal programmatically.