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
15 Hrs
30 Min
16 Seg
Curso de Backend con ExpressJS

Curso de Backend con ExpressJS

Oscar Barajas Tavares

Oscar Barajas Tavares

CRUD

10/30
Resources

Creating a RESTful API is a fundamental skill for any modern web developer. In this article, we will explore how to implement the PUT operation in our CRUD, allowing us to update user records effectively. We will learn how to handle dynamic routes, process parameters and update data in a JSON file, all while identifying potential issues and best practices.

How to implement the PUT operation in a RESTful API?

Continuing with our CRUD development, we will now focus on the PUT operation, which allows us to update existing user information. This operation is essential in any application that handles persistent data.

To correctly implement a PUT endpoint, we need to:

  1. Define a dynamic route that accepts an identifier.
  2. Receive and process the updated data.
  3. Find the specific record to be modified.
  4. Apply the changes and save the updated information.

Let's start by defining our path in the application:

app.put('/users/:id', (req, res) => { // We get the user ID from the path parameters const userId = parseInt(req.params.id, 10);  
 // We get the updated data from the request body const updateUser = req.body;  
 // Logic to update the user // ...});

How to handle reading and updating data?

Once our path is defined, we need to implement the logic to read the users file, find the specific user, update it and save the changes:

app.put('/users/:id', (req, res) => { const userId = parseInt(req.params.id, 10); const updateUser = req.body;  
 // We read the users file fs.readFile(userFilePath, 'utf8', (error, data) => { if (error) { return res.status(500).json({ error: "Error with data connection" }); }    
 // Parse the JSON data let users = JSON.parse(data);    
 // Update the user matching the ID users = users.map(user => { return user.id === userId ? { ...user, ...updateUser } : user; });    
 // We save the changes to the file fs.writeFile(userFilePath, JSON.stringify(users, null, 2), (err) => { if (err) { return res.status(500).json({ error: "Error updating user" }); }      
 // We reply with the updated user res.json(updateUser); }); }); });});

In this code:

  1. We convert the URL ID to an integer with parseInt().
  2. We extract the updated data from the request body.
  3. We read the existing user file.
  4. We use the map() method to go through all the users and update only the one that matches the provided ID.
  5. We save the changes to the file.
  6. We respond with the updated user.

What problems can arise when updating records?

During the implementation of the PUT operation, it is important to be aware of possible problems:

Duplicate IDs: If there are multiple records with the same ID in our database, they will all be updated when we try to modify a specific one. This can cause serious data inconsistencies.

For example, if we have two users with ID=1 and we update one of them, both records will be modified:

// Before the update[ { { id: 1, name: "Jane", email: "[email protected]" }, { id: 2, name: "Bob", email: "[email protected]" }, { id: 1, name: "Alice", email: "[email protected]" }]
// After updating the user with ID=1[ { { id: 1, name: "John Smith", email: "[email protected]" }, { id: 2, name: "Bob", email: "[email protected]" }, { id: 1, name: "John Smith", email: "[email protected]" }]

Lack of validations: It is crucial to implement validations to:

  • Verify that the ID exists before attempting to update.
  • Validate that the data sent complies with the expected format.
  • Ensure that there are no duplicate IDs in the database.

How to test our PUT implementation?

To test our implementation, we can use tools such as Postman:

  1. Create a new PUT request.
  2. Set the URL with the user ID to update (e.g. http://localhost:3000/users/1).
  3. Set the body of the request with the updated data in JSON format:
{ " name": "John Smith", " email": "[email protected]"}
  1. Send the request and check the response.
  2. Check that the changes have been applied correctly in our user file.

Important: Always verify that the changes have been applied correctly and only to the desired records.

The implementation of the PUT operation is fundamental for any complete RESTful API. With proper validation and error handling, we can ensure that our data remains consistent and that updates are applied accurately. Have you ever implemented an API with CRUD operations? Share your experience in the comments.

Contributions 0

Questions 0

Sort by:

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