Add a REST endpoint
REST-style endpoints can be defined as part of a plugin.
REST endpoints are implemented as NestJS Controllers. For comprehensive documentation, see the NestJS controllers documentation.
In this guide we will define a plugin that adds a single REST endpoint at http://localhost:3000/products which returns a list of all products.
Create a controller
First let's define the controller:
The key points to note here are:
- The
@Controller()decorator defines the base path for all endpoints defined in this controller. In this case, all endpoints will be prefixed with/products. - The
@Get()decorator defines a GET endpoint at the base path. The method namefindAllis arbitrary. - The
@Ctx()decorator injects the RequestContext which is required for all service methods.
Register the controller with the plugin
Note: The PluginCommonModule should be imported to gain access to Vendure core providers - in this case it is required in order to be able to inject ProductService into our controller.
The plugin can then be added to the VendureConfig:
Controlling access to REST endpoints
You can use the @Allow() decorator to declare the permissions required to access a REST endpoint:
The following Vendure API decorators can also be used with NestJS controllers: @Allow(), @Transaction(), @Ctx().
Additionally, NestJS supports a number of other REST decorators detailed in the NestJS controllers guide