You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesi贸n a prueba de IA

Antes: $249

Currency
$209
Suscr铆bete

Termina en:

0 D铆as
14 Hrs
11 Min
24 Seg
Curso de Backend con ExpressJS

Curso de Backend con ExpressJS

Oscar Barajas Tavares

Oscar Barajas Tavares

Solicitudes POST

9/30
Resources

Creating RESTful APIs is a fundamental skill for any modern web developer. In this content, we will explore how to implement the POST method to create new users in our API, an essential step to build applications that allow user registration. You will learn how to receive data, validate it and store it correctly, laying the foundation for full CRUD operations.

How to implement the POST method to create users in an API?

When developing an API, we need to allow clients to create new resources. In this case, we will implement an endpoint that uses the HTTP POST method to create new users in our application.

To start, we need to create a new entry point in our application. Although we already had an endpoint to get users with GET, we will now create one that uses POST for the same route:

app.post('/users', (req, res) => { // Code to create a new user});

This is a clear example of how the same route can have different behaviors depending on the HTTP method used, one of the fundamental principles of RESTful APIs.

How to obtain and process the data sent by the client?

When a client sends a POST request, it usually includes data in the body of the request. Thanks to the integration of BodyParser in our application, we can easily access this data:

const newUser = req.body;

This simple line allows us to capture all the information that the client is sending. The expected structure for a user might look something like:

{ " id": 3, " name": "NewUser", " email": "[email protected]"}

How to validate the received data?

Before saving a new user, it is crucial to validate that the data received meets our requirements. Some common validations include:

  • Verify that the name has at least 3 characters.
  • Checking that the email is in a valid format
  • Making sure that the ID is unique

To implement these validations, we could use code like the following:

// Name validationif (!newUser.name || newUser.name.length < 3) { return res.status(400).json({ error: "Name must be at least 3 characters" });}
// Validating the email with regular expressionconst emailRegex = /^[^[^\s@]+@[^\s@]+@.[^^[^\s@]+$/;if (!newUser.email || !emailRegex.test(newUser.email)) { return res.status(400).json({ error: "The email is invalid" });} }

How to read and update existing data?

To save a new user, we first need to read the existing users. We will use the fs (File System) module of Node.js for this:

const fs = require('fs');
 fs.readFile(userFilePath, 'utf-8', (error, data) => { if (error) { return res.status(500).json({ error: "Error with data connection" }); }  
 const users = JSON.parse(data);  
 // Here we continue with the process});

Once we have the existing users, we can add the new user and save the updated information:

// Add the new userusers.push(newUser);
// Save the updated informationfs.writeFile(userFilePath, JSON.stringify(users, null, 2), (error) => { if (error) { return res.status(500).json({ error: "Error saving user" }); }  
 // Reply with the created user res.status(201).json(newUser);});

We use the HTTP status code 201 (Created) to indicate that the resource has been successfully created, following RESTful API design best practices.

How to test our POST endpoint?

Unlike GET endpoints, we cannot test a POST endpoint by simply visiting a URL in the browser. We need a tool like Postman:

  1. Create a new request in Postman
  2. Select the POST method
  3. Enter the URL of our endpoint (e.g. http://localhost:3000/users)
  4. In the "Body" tab, select "raw" and "JSON".
  5. Enter the new user's data in JSON format
  6. Send the request

If everything works correctly, we will receive a response with code 201 and the data of the created user. We can verify that the user has been saved correctly by making a GET request to /users.

What improvements could we implement?

Although our endpoint works, there are several improvements we could implement:

  • Unique ID validation: Currently, we are not checking if the ID already exists, which could cause problems.
  • Automatic ID generation: Instead of requiring the client to provide an ID, we could generate it automatically.
  • More robust error handling: We could implement a more complete system to handle different types of errors.
  • Encapsulation of repeated code: We noticed that there is code that is repeated (such as reading the file) that could be encapsulated in reusable functions.

These improvements would help us to create a more robust and maintainable API, following software design principles such as DRY (Don't Repeat Yourself) and separation of responsibilities.

Implementing the POST method is just the beginning. In future lessons, we will learn how to use the PUT method to update existing information, thus completing more CRUD operations in our API.

Have you implemented validations in your APIs? Share in the comments how you handle data validation in your projects and what strategies you use to ensure data integrity.

Contributions 0

Questions 0

Sort by:

Want to see more contributions, questions and answers from the community?