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
Data validation is a fundamental aspect in the development of RESTful APIs to guarantee the integrity and consistency of the information. Implementing proper validations at the POST and PUT endpoints prevents errors that could compromise the entire database and ensures that the application works correctly. These practices not only improve code quality, but also provide a better end-user experience.
When developing APIs, it is crucial to validate the data we receive before processing it. In this case, we have used artificial intelligence as a tool to generate robust validations for our endpoints. The implementation of these validations allows us to control the quality of the data entering our system.
The validations we have implemented include:
These validations have been encapsulated in reusable functions that can be shared between the backend and frontend if necessary.
The validation functions we have created are:
// Email validation using Regexfunction isValidEmail(email) { const emailRegex = /^[^^^^s@]+@[^^^s@]+@[^^^s@]+$/; return emailRegex.test(email);}
// Name validation (minimum 3 characters)function isValidName(name) { return typeof name === 'string' && name.length >= 3;}
// ID validation (numeric and unique)function isValidId(id, users) { const isNumeric = !isNaN(id); const isUnique = !users.some(user => user.id === id); return isNumeric && isUnique;}
// Main validation functionfunction validateUser(user, users) { const errors = [];
if (!isValidName(user.name)) { errors.push("Name must be at least three characters"); }
if (!isValidEmail(user.email)) { errors.push("The email is invalid"); }
if (!isValidId(user.id, users)) { errors.push("The ID must be numeric and unique"); } }
return { isValid: errors.length === 0, errors: errors };}
These functions are stored in a file called validation.js
inside the utilities folder, allowing them to be easily imported anywhere in our application.
To integrate these validations in our POST and PUT endpoints, we need to import the main function validateUser
and use it before processing the data:
import { validateUser } from './utils/validation.js';
// In the POST endpointapp.post('/users', (req, res) => { const newUser = req.body; const validation = validateUser(newUser, users);
if (!validation.isValid) { return res.status(400).json({ error: validation.errors }); }
// Continue with the logic to create the user users.push(newUser); res.status(201).json(newUser);});
// At the PUT endpointapp.put('/users/:id', (req, res) => { const updatedUser = req.body; const validation = validateUser(updatedUser, users);
if (!validation.isValid) { return res.status(400).json({ error: validation.errors }); }
// Continue with the logic to update the user // ...});
To verify that our validations work correctly, we can use tools like Postman to send different types of requests to our endpoints:
By testing these cases, we should receive appropriate responses:
A common challenge is the validation on the PUT endpoint. As observed in testing, there can be a conflict when trying to update an existing user, as the unique ID validation might reject the operation incorrectly.
This is an interesting challenge: to modify the validation function to allow updating an existing user without the unique ID validation interfering. A possible solution would be to adapt the isValidId
function to consider the context of the operation (creation vs. update).
Implementing robust validations is a fundamental step in building reliable and secure APIs. These practices not only prevent data errors, but also improve the user experience by providing clear and specific error messages. Have you faced similar challenges in your projects? Share your experiences and solutions in the comments.
Contributions 1
Questions 0
Want to see more contributions, questions and answers from the community?