Another ExpressJS API tutorial for 2021, part 04— Configuring controllers
In our article number 4 we are going to configure controllers for our API using ExpressJS!

Hi, if you are arriving to this series of articles for the first time then here is what you are missing: This is a series of small articles that will guide you up to build an API using ExpressJS with Typescript.
Just as a quick overview, here is the series of articles that we are writing:
- Create your hello world ExpressJS API (Yes… we always need to start with a hello world)
- Configure our hello world application to use Typescript (TS is cool, believe me ;) )
- Create our first CRUD API endpoints for an user (Everyone wants a registered user in their applications, no?)
- Create and configure your controllers (We will talk about it after) We are here now ;)
- Create and configure your services (What the h. is that?)
- Middleware’s! (Yes, we need and use it everyday)
- End to end testings!
- Configuring a secure way to manage user permissions via API
- Putting all together into a Docker container
- Configuring a simple MongoDB to connect to our application
- Configuring permission level to the application
- Add logs with Winston!
Now that we made all the overview, let’s start on the controllers!
At our last article, we finished the routes configuration for an USER resource. You can grab the code here.
Our target now is to build a structure that would work for better code maintenance and to easy it up the way we will read the code.
We have now something like the following:
this.app.get(`/users`, (req: express.Request, res: express.Response) => {
res.status(200).send(`List of users`);
});
Using ExpressJS, we first define the HTTP method (*get* in this case), then we pass the name of the endpoint (‘/users’) and after we pass a function that will handle the request. But, for a standard of coding, it is a nice idea to use the routes configuration file just to set up the name of the endpoints and who are the responsible of dealing with it. This last part we will call as Controller.
ExpressJS also allows us to pass several functions at the request in order to do specific handlings before sending an answer to the client.
What we want to do is the following:
this.app.get(`/users`, [
UserController.listUsers
]);
We are now passing an array []
and using a UserController (that we will create now)
We will be using more functions as Middlewares in our next article! Don’t worry much about
[]
now
So, before finishing the routes, let’s create our controller. First of all, let’s create a folder called controllers
inside the users
folder. Now, create the file users.controller.ts
and add the following code:
import express from 'express';export class UsersController {listUsers(req: express.Request, res: express.Response) {
res.status(200).send(`Get to users`);
}getUserById(req: express.Request, res: express.Response) {
res.status(200).send(`Get to user ${req.params.userId}`);
}createUser(req: express.Request, res: express.Response) {
res.status(200).send(`Post to user ${req.params.userId}`);
}patch(req: express.Request, res: express.Response) {
res.status(200).send(`Patch to user ${req.params.userId}`);
}put(req: express.Request, res: express.Response) {
res.status(200).send(`Put to user ${req.params.userId}`);
}removeUser(req: express.Request, res: express.Response) {
res.status(200).send(`Delete to user ${req.params.userId}`);
}}
For now it seems that we just removed code from the routes file and put into the Controller without coding anything further. For this article we won’t go much further but in the future articles we are going to develop more coding using this approach. Just keep following it ;)
Great, now we can add the UsersController to the User’s routes! Let’s open back again the user.routes.config.ts
and update the code:
import {CommonRoutesConfig, configureRoutes} from '../common/common.routes.config';
import {UsersController} from './controllers/users.controller';import express from 'express';export class UsersRoutes extends CommonRoutesConfig implements configureRoutes{
constructor(app: express.Application) {
super(app, 'UsersRoute');
this.configureRoutes();
}configureRoutes() {
const usersController = new UsersController();
this.app.get(`/users`, [
usersController.listUsers
]);this.app.post(`/users`, [
usersController.createUser
]);this.app.put(`/users/:userId`, [
usersController.put
]);this.app.patch(`/users/:userId`, [
usersController.patch
]);this.app.delete(`/users/:userId`, [
usersController.removeUser
]);
this.app.get(`/users/:userId`, [
usersController.getUserById
]);
}}
And that’s it, if you run npm start
and the code should be working normally.
In the next article we are going to talk and implement properly the user controller to have it working better. We will also be using a concept of services to add a temporary database that in one of the lates articles to be changed to a Mongo database. Hope to see you all there ;)
Thanks for reading and see you at the next article!
tips:
- the full code of this article is HERE
- don’t forget to use a nice app to test your API such as Postman or Insomnia
- I know you still didn’t… Read the ExpressJS documentation!
- Book suggestion: Clean Code and again Design Patterns
- Brazilian? PT-BR Book suggestion: Clean Code and Design Patterns
- Complete project is here!