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 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.
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.
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]"}
Before saving a new user, it is crucial to validate that the data received meets our requirements. Some common validations include:
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" });} }
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.
Unlike GET endpoints, we cannot test a POST endpoint by simply visiting a URL in the browser. We need a tool like Postman:
http://localhost:3000/users)
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
.
Although our endpoint works, there are several improvements we could implement:
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
Want to see more contributions, questions and answers from the community?