Can I expose an collection entry in draft-mode in the api for a certain user

An entry not published is not exposed in the api.
Is there a way to do this for a certain user, so that the user (and only this user) can query the api for all entries, also unpublished?

1 Like

Here is an example for Mongo.

First, create a new route:

{
      "method": "GET",
      "path": "/findUnpublished",
      "handler": "articles.findUnpublished",
      "config": {
        "policies": []
      }
    },

Seconds, create a new controller function, called findUnpublished:

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

module.exports = {
  async findUnpublished(ctx) {

    //getting all the existing articles, no metter if they have unpublished status
    let result = await strapi.query('articles').model.find();
    
    //sanitize them to hide all private fields
    let articles = sanitizeEntity(result, {
        model: strapi.models['articles'],
    });
    
    //return result to the /findUnpublished API
    ctx.send(articles);
  }
};

Now add create a new role called CanViewUnpublished (as an example) and assign access to the newly created controller: findUnpublished
image

And the last step, create a new user and assign that role(CanViewUnpublished ) to him.

Voila, result:

image

1 Like

Great, thank you!
I had to change

to

let result = await strapi.query('articles').find();

and it worked.

If you want to avoid creating the route/controller, you can already search for those through the API by adding this after your article →
?_publicationState=preview&published_at_null=true

Example:
http://localhost:1337/articles?_publicationState=preview&published_at_null=true

more info here → Content API - Strapi Developer Documentation

4 Likes

Just FYI, the format for this has changed. To get draft content, you now append this to your query:

?publicationState=preview

And if you want ONLY unpublished content, you can do this:

?publicationState=preview&filters[publishedAt][$null]=true

From Filtering, Locale, and Publication State for REST API - Strapi Developer Docs (v4 documentation)

4 Likes