Payload CMS is not only a powerful content management system but also provides flexibility for developers to create custom API endpoints. These endpoints allow you to extend the CMS’s functionality, tailor API responses, and integrate third-party systems seamlessly.
Steps to Create a Custom Endpoint
- Access Collection Configuration: Open the configuration file of the collection where you want the custom endpoint.
- Add the Endpoint: Define an endpoints array in the collection configuration
import { buildConfig } from 'payload/config';
const Collections = [
{
slug: 'products',
fields: [
{ name: 'title', type: 'text', required: true },
{ name: 'price', type: 'number', required: true },
],
endpoints: [
{
path: '/list',
method: 'get',
handler: async (req, res) => {
const products = await req.payload.find({ collection: 'products' });
res.status(200).json({ data: products.docs });
},
},
],
},
];
export default buildConfig({ collections: Collections });
Start the Payload server and make a request to your custom endpoint
GET http://localhost:3000/api/products/list
Conclusion
Custom API endpoints in Payload CMS provide the flexibility to meet unique project requirements. By following this straightforward process, you can efficiently create and use tailored endpoints to enhance the functionality of your applications. This approach simplifies integrations and ensures your CMS adapts to specific use cases.