For this example we will be using the article collection content type defined below for the implementation
path: /strapi-project/src/api/article/content-types/article/schema.json
{
"kind": "collectionType",
"collectionName": "articles",
"info": {
"singularName": "article",
"pluralName": "articles",
"displayName": "Article"
},
"options": {
"draftAndPublish": true
},
"pluginOptions": {},
"attributes": {
"title": {
"type": "string"
},
"slug": {
"type": "uid",
"targetField": "title"
}
}
}
We can then customize the findOne controller to accept a slug over id
path: /strapi-project/src/api/article/controllers/article.js
"use strict";
/**
* article controller
*/
const _ = require("lodash");
const {
transformParamsToQuery,
pickSelectionParams,
} = require("@strapi/strapi/lib/services/entity-service/params");
const { createCoreController } = require("@strapi/strapi").factories;
const ENTITY_UID = "api::article.article";
module.exports = createCoreController(ENTITY_UID, ({ strapi }) => ({
async findOne(ctx) {
const { id } = ctx.params;
const queryParams = ctx.query || {};
// build default query structure
const query = transformParamsToQuery(
ENTITY_UID,
pickSelectionParams(queryParams)
);
// add slug constraint to all requests
_.set(query, ["where", "slug", "$eq"], id);
const entity = await strapi.db.query(ENTITY_UID).findOne(query);
// sanitize response to ensure permissions are respected
const sanitizedEntity = await this.sanitizeOutput(entity, ctx);
// transform response to uniform API response format
return this.transformResponse(sanitizedEntity);
},
}));
Note: The where parameter here is of the WhereParameter type
The endpoint can then be queried by slug instead of id
http://localhost:1337/api/articles/lorem-ipsum
which will return the following response
{
"data": {
"id": 1,
"attributes": {
"title": "lorem ipsum",
"slug": "lorem-ipsum",
"createdAt": "2022-04-06T03:53:11.345Z",
"updatedAt": "2022-04-06T03:53:24.671Z",
"publishedAt": null
}
},
"meta": {}
}
A not found error will be returned if no entities for the content type match the provided slug.
If you want all of this handled for you with multiple content type support, additional control over the slugification process as well as other useful features I would recommend the strapi-plugin-slugify.
Hey @ComfortablyCoding Thank you so much, this worked!