Services are a set of reusable functions. They are particularly useful to respect the "don’t repeat yourself" (DRY) programming concept and to simplify controllers logic.
Services can be generated or added manually. Strapi provides a
createCoreService factory function that automatically generates core services and allows building custom ones or extend or replace the generated services.
# Adding a new service
A new service can be implemented:
- with the interactive CLI command
./src/api/[api-name]/services/for API services
./src/plugins/[plugin-name]/services/for plugin services.
To manually create a service, export a factory function that returns the service implementation (i.e. an object with methods). This factory function receives the
🤓 Entity Service API
To get started creating your own services, see Strapi's built-in functions in the Entity Service API documentation.
Example of a custom email service (using Nodemailer)
The goal of a service is to store reusable functions. A
sendNewsletter service could be useful to send emails from different functions in our codebase that have a specific purpose:
The service is now available through the
strapi.service('api::restaurant.restaurant').sendNewsletter(...args) global variable. It can be used in another part of the codebase, like in the following controller:
When a new content-type is created, Strapi builds a generic service with placeholder code, ready to be customized.
# Extending core services
Core services are created for each content-type and could be used by controllers to execute reusable logic through a Strapi project. Core services can be customized to implement your own logic. The following code examples should help you get started.
A core service can be replaced entirely by creating a custom service and naming it the same as the core service (e.g.
Collection type examples
Single type examples
Once a service is created, it's accessible from controllers or from other services:
// access an API service strapi.service('api::apiName.serviceName'); // access a plugin service strapi.service('plugin::pluginName.serviceName');
To list all the available services, run
yarn strapi services:list.