Creating Resources (POST)
How to create JSON:API resources using NextDrupal client.
The createResource
and createFileResource
helpers are available in next-drupal ^1.4.0
.
If you're working with JSON:API, be mindful to select the option:
Accept all JSON:API create, read, update, and delete operations.
on the following path: /admin/config/services/jsonapi
in Drupal.
The NextDrupal
client ships with createResource
and 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. })