avatarMarcos Henrique da Silva

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

5381

Abstract

js-number">200</span>).<span class="hljs-title function_">send</span>(<span class="hljs-string">List of users</span>); });</pre></div><div id="4539"><pre><span class="hljs-variable language_">this</span>.<span class="hljs-property">app</span>.<span class="hljs-title function_">post</span>(<span class="hljs-string">/users</span>, <span class="hljs-function">(<span class="hljs-params">req: express.Request, res: express.Response</span>) =></span> { res.<span class="hljs-title function_">status</span>(<span class="hljs-number">200</span>).<span class="hljs-title function_">send</span>(<span class="hljs-string">Post to users</span>); });</pre></div><div id="8a19"><pre><span class="hljs-variable language_">this</span>.<span class="hljs-property">app</span>.<span class="hljs-title function_">put</span>(<span class="hljs-string">/users/:userId</span>, <span class="hljs-function">(<span class="hljs-params">req: express.Request, res: express.Response</span>) =></span> { res.<span class="hljs-title function_">status</span>(<span class="hljs-number">200</span>).<span class="hljs-title function_">send</span>(<span class="hljs-string">Put to <span class="hljs-subst">${req.params.userId}</span></span>); });</pre></div><div id="2f3d"><pre><span class="hljs-variable language_">this</span>.<span class="hljs-property">app</span>.<span class="hljs-title function_">patch</span>(<span class="hljs-string">/users/:userId</span>, <span class="hljs-function">(<span class="hljs-params">req: express.Request, res: express.Response</span>) =></span> { res.<span class="hljs-title function_">status</span>(<span class="hljs-number">200</span>).<span class="hljs-title function_">send</span>(<span class="hljs-string">Patch to <span class="hljs-subst">${req.params.userId}</span></span>); });</pre></div><div id="b18b"><pre><span class="hljs-variable language_">this</span>.<span class="hljs-property">app</span>.<span class="hljs-title function_">delete</span>(<span class="hljs-string">/users/:userId</span>, <span class="hljs-function">(<span class="hljs-params">req: express.Request, res: express.Response</span>) =></span> { res.<span class="hljs-title function_">status</span>(<span class="hljs-number">200</span>).<span class="hljs-title function_">send</span>(<span class="hljs-string">Delete to <span class="hljs-subst">${req.params.userId}</span></span>); });</pre></div><div id="5516"><pre> <span class="hljs-variable language_">this</span>.<span class="hljs-property">app</span>.<span class="hljs-title function_">get</span>(<span class="hljs-string">/users/:userId</span>, <span class="hljs-function">(<span class="hljs-params">req: express.Request, res: express.Response</span>) =></span> { res.<span class="hljs-title function_">status</span>(<span class="hljs-number">200</span>).<span class="hljs-title function_">send</span>(<span class="hljs-string">Get to <span class="hljs-subst">${req.params.userId}</span></span>); }); }</pre></div><div id="c256"><pre>}</pre></div><p id="04cd">We are extending the CommonRoutesConfig file in order to have access to common attributes and to avoid to code it again and again and again.</p><p id="0782">Also, we are using the <code>implements</code> <b>configureRoutes </b>to force our users routes to implement the method called <code>configureRoutes</code> and call it at our constructor.</p><p id="6c03">We also want to receive an <b>app</b> that will be an <b>express.Application </b>and that will allow us to create some endpoints</p><p id="74a1">The HTTP requests that we used are:</p><p id="109c" type="7">get: we will use this to retrieve a single resource or a list of resources</p><p id="60bd" type="7">post: we will use this to create a new resource</p><p id="7613" type="7">put: we will use this to update an entire resource</p><p id="055a" type="7">patch: we will use this to update a part of a specific resource</p><p id="4a5b" type="7">delete: we will use this to remove a specific resource</p><p id="b66a">In this article we are <b>not implementing</b> these endpoints but just configuring it to reply an answer showing that they are working. The description above shows a highly recommended suggestion on how to define your HTTP requests and easy it up the future code maintenance and to onboard new developers who will work within the same project.</p><blockquote id="f9bf"><p>Note: you will probably not be able to test using a browser url, since it will only requests <b>GET</b> methods. I would recommend for testing either <a href="https://www.postman.com/">postman</a> or <a href="https://insomnia.rest/">insomnia</a></p></blockquote><p id="4eda">The least but not last is to update our <b>app.ts</b> and say to it that we have new routes to be running on our API. Let’s update the <b>app.ts</b> as the following:</p><div id="8dfa"><pre><span class="hljs-keyword">import</span> express <span class="hljs-keyword">from</span> <span class="hljs-string">'express'</span>; <span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> http <span class="hljs-keyword">from</span> <span class="hljs-string">'http'</span>;</pre></div><div id="231d"><pre><span class="hljs-keyword">import</span> {CommonRoutesConfig} <span class="hljs-keyword"

Options

from</span> <span class="hljs-string">'./common/common.routes.config'</span>; <span class="hljs-keyword">import</span> {UsersRoutes} <span class="hljs-keyword">from</span> <span class="hljs-string">'./users/users.routes.config'</span>;</pre></div><div id="081c"><pre><span class="hljs-type">const</span> app: express.Application = <span class="hljs-built_in">express</span>(); <span class="hljs-type">const</span> server: http.<span class="hljs-built_in">Server</span> = http.<span class="hljs-built_in">createServer</span>(app); <span class="hljs-type">const</span> port = <span class="hljs-number">3000</span>; <span class="hljs-type">const</span> routes: any = []; routes.<span class="hljs-built_in">push</span>(<span class="hljs-keyword">new</span> <span class="hljs-built_in">UsersRoutes</span>(app));</pre></div><div id="ec93"><pre>app.<span class="hljs-title function_">get</span>(<span class="hljs-string">'/'</span>, <span class="hljs-function">(<span class="hljs-params">req: express.Request, res: express.Response</span>) =></span> { res.<span class="hljs-title function_">status</span>(<span class="hljs-number">200</span>).<span class="hljs-title function_">send</span>(<span class="hljs-string">Server running at port <span class="hljs-subst">${port}</span></span>) });</pre></div><div id="7122"><pre>server.listen(port, () => { <span class="hljs-built_in">console</span>.<span class="hljs-built_in">log</span>(<span class="hljs-string">Server running at port <span class="hljs-subst">${port}</span></span>); routes.forEach(<span class="hljs-function">(<span class="hljs-params">route: CommonRoutesConfig</span>) =></span> { <span class="hljs-built_in">console</span>.<span class="hljs-built_in">log</span>(<span class="hljs-string">Routes configured for <span class="hljs-subst">${route.getName()}</span></span>); }); });</pre></div><p id="74d0">We created an array called routes which we will be adding new routes there. After server.listen will callback our function we will be printing at the console the route name to be sure that everything is working as expected.</p><p id="1c25">As for testing, we just need to run at our terminal <code>npm start</code> and open either insomnia/postman and try a get, post, put, delete to see the console logs for:</p><div id="1709"><pre><span class="hljs-built_in">get</span> <span class="hljs-keyword">to</span> localhost:3000/users</pre></div><div id="5e9d"><pre><span class="hljs-built_in">post</span> <span class="hljs-built_in">to</span> localhost:<span class="hljs-number">3000</span>/users</pre></div><div id="4576"><pre><span class="hljs-keyword">put</span> <span class="hljs-keyword">to</span> localhos<span class="hljs-variable">t:3000</span>/users/:userId</pre></div><div id="ea81"><pre>patch <span class="hljs-keyword">to</span> localhost:<span class="hljs-number">3000</span>/users/:<span class="hljs-keyword">user</span>Id</pre></div><div id="dbba"><pre><span class="hljs-keyword">delete</span> <span class="hljs-keyword">to</span> localhos<span class="hljs-variable">t:3000</span>/users/:userId</pre></div><div id="3d6c"><pre><span class="hljs-built_in">get</span> <span class="hljs-keyword">to</span> localhost:3000/users/:userId</pre></div><blockquote id="5e00"><p>Remember to change <b>:userId</b> to any random character that you want by this time. In the future articles we will implement and control the <b>:userId</b></p></blockquote><p id="3668">The next article we will be talking about controllers and a suggestion to how to use and implement them to easy it up our coding for the future.</p><p id="015e">Thanks for reading and see you at the <a href="https://readmedium.com/another-expressjs-api-tutorial-for-2020-part-04-configuring-controllers-f748d2477295">next article</a>!</p><div id="51a1" class="link-block"> <a href="https://readmedium.com/another-expressjs-api-tutorial-for-2020-part-04-configuring-controllers-f748d2477295"> <div> <div> <h2>Another ExpressJS API tutorial for 2020, part 04— Configuring controllers</h2> <div><h3>In our article number 4 we are going to configure controllers for our API using ExpressJS!</h3></div> <div><p>medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/1*eWYm3Dm7s0t8lLWYRW4pow.jpeg)"></div> </div> </div> </a> </div><p id="a273">tips:</p><ul><li>the full code of this article is <a href="https://github.com/makinhs/expressjs-api-tutorial/tree/003-configurando-primeiras-rotas">HERE</a></li><li>don’t forget to use a nice app to test your API such as <a href="https://www.postman.com/">Postman</a> or <a href="https://insomnia.rest/">Insomnia</a></li><li>I know you still didn’t… Read the ExpressJS <a href="https://expressjs.com/en/4x/api.html">documentation</a>!</li><li>Book suggestion: <a href="https://amzn.to/3dgcWwI">Clean Code</a> and again <a href="https://amzn.to/2WGb1f5">Design Patterns</a></li><li>Brazilian? PT-BR Book suggestion: <a href="https://amzn.to/2wnMel1">Clean Code</a> and <a href="https://amzn.to/2U6uXWI">Design Patterns</a></li><li>Complete project is <a href="https://github.com/makinhs/expressjs-api-tutorial">here</a>!</li></ul></article></body>

Another ExpressJS API tutorial for 2021, part 03— Managing your user endpoints

In this third part of the articles, we would create our first CRUD endpoint for an user resource

Hi again, this is a series of articles to help you to develop an API using ExpressJS with Typescript. We’ve finished our last article configuring a Typescript project for ExpressJS. You can get the Github code here.

Just as a quick overview, here is the series of articles that we are writing:

Let’s put our hands on the code now!

First off all, at the root of the project, let’s create a folder called common which we will share some files into the application in order to reuse code.

Now, let’s create a file called common.routes.config.ts with the following:

import express from 'express';
export class CommonRoutesConfig {
    app: express.Application;
    name: string;
constructor(app: express.Application, name: string) {
        this.app = app;
        this.name = name;
    }
getName() {
        return this.name;
    }
}
export interface configureRoutes {
}

This is not a mandatory step to create an API but I we will use this as an example on how to use extends and implements with Typescript for who is still beginning on it.

Now we will create our first endpoints. For that, let’s create at our root project a folder called users and inside of it a file called users.routes.config.ts with the following code:

import {CommonRoutesConfig, configureRoutes} from '../common/common.routes.config';
import express from 'express';
export class UsersRoutes extends CommonRoutesConfig implements configureRoutes{
    constructor(app: express.Application) {
        super(app, 'UsersRoute');
        this.configureRoutes();
    }
configureRoutes() {
        this.app.get(`/users`, (req: express.Request, res: express.Response) => {
            res.status(200).send(`List of users`);
        });
this.app.post(`/users`, (req: express.Request, res: express.Response) => {
            res.status(200).send(`Post to users`);
        });
this.app.put(`/users/:userId`, (req: express.Request, res: express.Response) => {
            res.status(200).send(`Put to ${req.params.userId}`);
        });
this.app.patch(`/users/:userId`, (req: express.Request, res: express.Response) => {
            res.status(200).send(`Patch to ${req.params.userId}`);
        });
this.app.delete(`/users/:userId`, (req: express.Request, res: express.Response) => {
            res.status(200).send(`Delete to ${req.params.userId}`);
        });
        this.app.get(`/users/:userId`, (req: express.Request, res: express.Response) => {
            res.status(200).send(`Get to ${req.params.userId}`);
        });
    }
}

We are extending the CommonRoutesConfig file in order to have access to common attributes and to avoid to code it again and again and again.

Also, we are using the implements configureRoutes to force our users routes to implement the method called configureRoutes and call it at our constructor.

We also want to receive an app that will be an express.Application and that will allow us to create some endpoints

The HTTP requests that we used are:

get: we will use this to retrieve a single resource or a list of resources

post: we will use this to create a new resource

put: we will use this to update an entire resource

patch: we will use this to update a part of a specific resource

delete: we will use this to remove a specific resource

In this article we are not implementing these endpoints but just configuring it to reply an answer showing that they are working. The description above shows a highly recommended suggestion on how to define your HTTP requests and easy it up the future code maintenance and to onboard new developers who will work within the same project.

Note: you will probably not be able to test using a browser url, since it will only requests GET methods. I would recommend for testing either postman or insomnia

The least but not last is to update our app.ts and say to it that we have new routes to be running on our API. Let’s update the app.ts as the following:

import express from 'express';
import * as http from 'http';
import {CommonRoutesConfig} from './common/common.routes.config';
import {UsersRoutes} from './users/users.routes.config';
const app: express.Application = express();
const server: http.Server = http.createServer(app);
const port = 3000;
const routes: any = [];
routes.push(new UsersRoutes(app));
app.get('/', (req: express.Request, res: express.Response) => {
    res.status(200).send(`Server running at port ${port}`)
});
server.listen(port, () => {
    console.log(`Server running at port ${port}`);
    routes.forEach((route: CommonRoutesConfig) => {
        console.log(`Routes configured for ${route.getName()}`);
    });
});

We created an array called routes which we will be adding new routes there. After server.listen will callback our function we will be printing at the console the route name to be sure that everything is working as expected.

As for testing, we just need to run at our terminal npm start and open either insomnia/postman and try a get, post, put, delete to see the console logs for:

get to localhost:3000/users
post to localhost:3000/users
put to localhost:3000/users/:userId
patch to localhost:3000/users/:userId
delete to localhost:3000/users/:userId
get to localhost:3000/users/:userId

Remember to change :userId to any random character that you want by this time. In the future articles we will implement and control the :userId

The next article we will be talking about controllers and a suggestion to how to use and implement them to easy it up our coding for the future.

Thanks for reading and see you at the next article!

tips:

Expressjs
Api Development
Nodejs
Tutorial
Typescript
Recommended from ReadMedium