Creating Resources (POST)

How to create JSON:API resources using DrupalClient.


⚠️

The createResource and createFileResource helpers are available in next-drupal ^1.4.0.

The DrupalClient ships with a createResource and a createFileResource methods for creating JSON:API resources.


createResource

Create Resource

Create an article with a title and a body.

const article = await drupal.createResource("node--article", {
data: {
attributes: {
title: "Title of Article",
body: {
value: "<p>Content of body field</p>",
format: "full_html",
},
},
},
})

Create Resource with Relationships

Create an article with a media field.

const article = await drupal.createResource("node--article", {
data: {
attributes: {
title: "Title of Article",
body: {
value: "<p>Content of body field</p>",
format: "full_html",
},
},
relationships: {
field_media_image: {
data: {
type: "media--image",
id: media.id,
},
},
},
},
})

See the API reference for createResource.


createFileResource

To create a file resource, you use the name of the file field on the parent entity.

Example: A media--image with a file field called field_media_image.

const file = await drupal.createFileResource("file--file", {
data: {
attributes: {
type: "media--image", // <-- The type of the parent resource.
field: "field_media_image", // <-- The name of the field on the parent resource.
filename: "filename.jpg",
file: await fs.readFile("/path/to/file.jpg"),
},
},
})

This will create a file--file resource.

You can then use this to create a new media--image with a relationship to the file--file.

const media = await drupal.createResource<DrupalMedia>("media--image", {
data: {
attributes: {
name: "Name for the media",
},
relationships: {
field_media_image: {
data: {
type: "file--file",
id: file.id,
},
},
},
},
})

See the API reference for createFileResource.


Authentication

To make authenticated requests when creating resources, use the withAuth option.

See the authentication docs for the supported authentication methods.

const article = await drupal.createResource(
"node--article",
{
data: {
attributes: {
title: "Title of Article",
body: {
value: "<p>Content of body field</p>",
format: "full_html",
},
},
}
},
{
withAuth: // <-- Your auth method here.
}
)