Overview

This is a continuation of the following series.

This time, we will register taxonomies and add them to content.

Registering Taxonomies

A taxonomy called ne_class was created in advance through the GUI. It can be listed at the following URL.

/jsonapi/taxonomy_term/ne_class

Below is the program for registering a new taxonomy. Please configure host, username, and password as appropriate.

payload = {
    "data": {
        "type": "taxonomy_term--ne_class",
        "attributes": {
            "name": "干瀬",
        }
    }
}

_type = "ne_class"

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

The following result is obtained.

{'jsonapi': {'version': '1.0',
  'meta': {'links': {'self': {'href': 'http://jsonapi.org/format/1.0/'}}}},
 'data': {'type': 'taxonomy_term--ne_class',
  'id': '17c70bd6-e6fc-46e2-bb5d-2377ba9c8ab8',
  ...

Adding to Content

A content type called Place was created in advance through the GUI. Additionally, field_ne_class was created and configured to use the above taxonomy ne_class as value candidates.

The taxonomy id obtained earlier is specified in the id of relationships.

payload = {
    "data": {
        "type": "node--place",
        "attributes": {
            "title": "xxx"
        },
        "relationships": {
            "field_ne_class": {
                "data": {
                    "type": "taxonomy_term--ne_class",
                    "id": "17c70bd6-e6fc-46e2-bb5d-2377ba9c8ab8",
                }
            }
        }
    }
}

_type = "place"

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

Summary

It appears that adding taxonomies and associating them with content can be done programmatically. There may be better methods, but I hope this serves as a useful reference.