In most cases, the controllers will contain the bulk of a project's business logic. But as a controller's logic becomes more and more complicated, it's a good practice to use services to organize the code into re-usable parts.
Controllers can be generated or added manually. Strapi provides a
createCoreController factory function that automatically generates core controllers and allows building custom ones or extend or replace the generated controllers.
# Adding a new controller
A new controller can be implemented:
- with the interactive CLI command
./src/api/[api-name]/controllers/for API controllers (this location matters as controllers are auto-loaded by Strapi from there)
- or in a folder like
./src/plugins/[plugin-name]/server/controllers/for plugin controllers, though they can be created elsewhere as long as the plugin interface is properly exported in the
strapi-server.jsfile (see Server API for Plugins documentation)
Example: GET /hello route calling a basic controller
GET /hello route is defined, the name of the router file (i.e.
index) is used to call the controller handler (i.e.
index). Every time a
GET /hello request is sent to the server, Strapi calls the
index action in the
hello.js controller, which returns
When a new content-type is created, Strapi builds a generic controller with placeholder code, ready to be customized.
# Extending core controllers
Default controllers and actions are created for each content-type. These default controllers are used to return responses to API requests (e.g. when
GET /api/articles/3 is accessed, the
findOne action of the default controller for the "Article" content-type is called). Default controllers can be customized to implement your own logic. The following code examples should help you get started.
An action from a core controller can be replaced entirely by creating a custom action and naming the action the same as the original action (e.g.
Collection type examples
Single type examples
# Attaching a controller to a route
Controllers are declared and attached to a route. Controllers are automatically called when the route is called, so controllers usually do not need to be called explicitly (see routes documentation).
You may also create routes, controllers, services, and bind them together, by using strapi generate
# Usage with services
services can call controllers, and in this case the following syntax should be used:
// access an API controller strapi.controller('api::api-name.controller-name'); // access a plugin controller strapi.controller('plugin::plugin-name.controller-name');
To list all the available controllers, run
yarn strapi controllers:list.