Introducci贸n a Node.js y Express
Node.js y Express
Entorno de trabajo
Variables de entorno
Rutas din谩micas
Body parser
Postman
CRUD
驴Que es una API Restful?
Solicitudes GET
Solicitudes POST
CRUD
Soluci贸n del reto de validaci贸n
Solicitudes DELETE
MIddlewares
Middlewares - logger
Middlewares - ErrorHandler
DB
Instalar Postgresql
Instalar Prisma y PostgreSQL Client
Prisma Models
JWT
Autenticaci贸n utilizando JSON Web Tokens (JWT)
Auth - Register
Auth - Login
Expres.js
Arquitectura
Arquitectura parte 2
Creaci贸n y Migraci贸n de Modelos con Prisma para Citas M茅dicas
Admin controllers / services
Admin controllers / services parte 2
Reservations
Reservations parte 2
Appointments
Deploy
PostgreSQL
Deploy
You don't have access to this class
Keep learning! Join and start boosting your career
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.
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:
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 // ...});
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:
parseInt()
.map()
method to go through all the users and update only the one that matches the provided ID.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:
To test our implementation, we can use tools such as Postman:
http://localhost:3000/users/1)
.{ " name": "John Smith", " email": "[email protected]"}
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
Want to see more contributions, questions and answers from the community?