javascript3 Min Read

How to Create Article by REST API and Configure only Author can Edit/Update/Delete articles

Gorav Singal

May 02, 2021

TL;DR

Create articles via Strapi REST API with JWT authentication and configure permissions so only the original author can edit, update, or delete their own articles.

How to Create Article by REST API and Configure only Author can Edit/Update/Delete articles

Introduction

In this post, we will see:

  • create a test user
  • Authenticate it via REST API
  • How we will create an Article using REST API.
  • How to configure that only Author can add/update/delete an article

So far, we have seen How to Configure permissions on Article

Create a Test User

  • Click on Users
  • Add new User

Get single Article

Authenticate the User

The REST end point for this is:

POST /auth/local

Body: 
{
  identifier: "email",
  password: ""
}

Authenticate User2

As you can see, once we authenticate user by REST API, we get a jwt token. Which will be used for authenticated other APIs, like create/update/delete.

Create an Article

POST /articles

Body:
{
  title: "",
  body: ""
}

Header:
Authorization: Bearer <jwt token>

Create Article

Edit or Update an Article

The process will remain same, only HTTP method will change

PUT /articles

Body:
{
  title: "",
  body: ""
}

Header:
Authorization: Bearer <jwt token>

Delete an Article

The process will remain same, only HTTP method will change

PUT /articles/<id>

Header:
Authorization: Bearer <jwt token>

Configure only Author can Update/Delete an Article

So far we have configured that authenticated users can create/update/delete articles. But, we do not want that any authenticated user will update other author’s articles.

We need to do little tweaking in strapi. Lets follow.

Save Author user details in Articles created.

Till now, there is no information saved that who created a particular article. Lets starting saving it.

  • Goto Content types builder.
  • Goto your Article type
  • Click on: “Add Another field”
  • Click on Relation type
  • On right side, select: “User (from users-permission)”
  • On left side, give it a name as “author”
  • Select relation as: “many-to-one”. It will show as: “User has many articles”

Add Author for Articles

Now, we need to start saving user information with created articles. For this, we need to write little code.

Open /api/article/controllers/article.js Replace file content with following:

const { parseMultipartData, sanitizeEntity } = require('strapi-utils');

module.exports = {
  /**
   * Create a record.
   *
   * @return {Object}
   */

  async create(ctx) {
    let entity;
    if (ctx.is('multipart')) {
      const { data, files } = parseMultipartData(ctx);
      data.author = ctx.state.user.id;
      entity = await strapi.services.article.create(data, { files });
    } else {
      ctx.request.body.author = ctx.state.user.id;
      entity = await strapi.services.article.create(ctx.request.body);
    }
    return sanitizeEntity(entity, { model: strapi.models.article });
  },
};

Save it.

Create Article again from REST API

Now when you submit the create article request again, you will have author information saved with each article. A sample response will look like:

{
    "_id": "608e66f33c976e44787564c4",
    "title": "How to create an Article2",
    "body": "I will explain the process",
    "published_at": "2021-05-02T08:46:43.948Z",
    "createdAt": "2021-05-02T08:46:43.952Z",
    "updatedAt": "2021-05-02T08:46:43.959Z",
    "__v": 0,
    "author": {
        "confirmed": true,
        "blocked": false,
        "_id": "608e0771a81d84396e94a1d8",
        "username": "test",
        "email": "[email protected]",
        "provider": "local",
        "createdAt": "2021-05-02T01:59:13.156Z",
        "updatedAt": "2021-05-02T01:59:13.163Z",
        "__v": 0,
        "role": "608d84c0dbb8e436fba3faa4",
        "id": "608e0771a81d84396e94a1d8"
    },
    "id": "608e66f33c976e44787564c4"
}

Restrict Author can Update only his Articles

Again, we will need to write little code for this. Open same file again: /api/article/controllers/article.js

Add following code:

  /**
   * Update a record.
   *
   * @return {Object}
   */

  async update(ctx) {
    const { id } = ctx.params;

    let entity;

    const [article] = await strapi.services.article.find({
      id: ctx.params.id,
      'author.id': ctx.state.user.id,
    });

    if (!article) {
      return ctx.unauthorized(`You can't update this entry`);
    }

    if (ctx.is('multipart')) {
      const { data, files } = parseMultipartData(ctx);
      entity = await strapi.services.article.update({ id }, data, {
        files,
      });
    } else {
      entity = await strapi.services.article.update({ id }, ctx.request.body);
    }

    return sanitizeEntity(entity, { model: strapi.models.article });
  },

In above code, while receiving update article request. We are checking if the authenticated user is the author of article asked. If yes, proceed else reject the call.

Restrict that Author can delete only his Articles

Similarly to restrict that users can delete only their articles. Write below code in same file: /api/article/controllers/article.js

async delete(ctx) {
    const { id } = ctx.params;

    let entity;

    const [article] = await strapi.services.article.find({
      id: ctx.params.id,
      'author.id': ctx.state.user.id,
    });

    if (!article) {
      return ctx.unauthorized(`You can't update this entry`);
    }

    if (ctx.is('multipart')) {
      const { data, files } = parseMultipartData(ctx);
      entity = await strapi.services.article.delete({ id }, data, {
        files,
      });
    } else {
      entity = await strapi.services.article.delete({ id }, ctx.request.body);
    }

    return sanitizeEntity(entity, { model: strapi.models.article });
  },

Next

In next post, we will see how to setup a Slug(Nice URL) system.

Share

Related Posts

Strapi Tutorial - How to Configure Slug to have Nice URLs for SEO

Strapi Tutorial - How to Configure Slug to have Nice URLs for SEO

Introduction In our previous posts, we have seen How to Create Article in Strapi…

Tutorial - How to Create a Content-type, and Configure User Permissions for REST APIs

Tutorial - How to Create a Content-type, and Configure User Permissions for REST APIs

Introduction In this post, we will see how we can create a content type. And…

Tutorial - How to Setup Strapi Backend with Mongodb

Tutorial - How to Setup Strapi Backend with Mongodb

Introduction In this step-by-step tutorial, we will setup strapi headless CMS…

How to use Draft.js WYSWYG with Next.js and Strapi Backend, Edit/Update Saved Article

How to use Draft.js WYSWYG with Next.js and Strapi Backend, Edit/Update Saved Article

Introduction This post is in contuation of our previous post: How to use Draft…

How to use Draft.js WYSWYG with Next.js and Strapi Backend, Create and View Article with Image Upload

How to use Draft.js WYSWYG with Next.js and Strapi Backend, Create and View Article with Image Upload

Introduction In this post, we will use in Next.js with strapi. And, we will…

How to Integrate Next.js with Strapi Backend and Create a common utility class for REST APIs

How to Integrate Next.js with Strapi Backend and Create a common utility class for REST APIs

Introduction In this post, we will integrate Next.js with Strapi fully. And we…

Latest Posts

AI Video Generation in 2025 — Models, Costs, and How to Build a Cost-Effective Pipeline

AI Video Generation in 2025 — Models, Costs, and How to Build a Cost-Effective Pipeline

AI video generation went from “cool demo” to “usable in production” in 2024-202…

AI Models in 2025 — Cost, Capabilities, and Which One to Use

AI Models in 2025 — Cost, Capabilities, and Which One to Use

Choosing the right AI model is one of the most impactful decisions you’ll make…

AI Image Generation in 2025 — Models, Costs, and How to Optimize Spend

AI Image Generation in 2025 — Models, Costs, and How to Optimize Spend

Generating one image with AI costs between $0.002 and $0.12. That might sound…

AI Coding Assistants in 2025 — Every Tool Compared, and Which One to Actually Use

AI Coding Assistants in 2025 — Every Tool Compared, and Which One to Actually Use

Two years ago, AI coding meant one thing: GitHub Copilot autocompleting your…

AI Agents Demystified — It's Just Automation With a Better Brain

AI Agents Demystified — It's Just Automation With a Better Brain

Let’s cut through the noise. If you read Twitter or LinkedIn, you’d think “AI…

Supply Chain Security — Protecting Your Software Pipeline

Supply Chain Security — Protecting Your Software Pipeline

In 2024, a single malicious contributor nearly compromised every Linux system on…