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 with Node.js is a fundamental skill for any modern backend developer. Learning how to properly structure your project and handle CRUD (Create, Read, Update, Delete) operations will allow you to build robust and scalable applications. This time, we will focus on implementing the GET method to retrieve user data from a local file, laying the groundwork for future database migration.
Before implementing any endpoint in our API, we need to configure our project to read and write files locally. Node.js provides native modules that facilitate these operations.
To get started, we need to import the necessary modules:
const fs = require('fs');const path = require('path');
The fs
(File System) module allows us to work with the file system, while path
helps us to handle file paths efficiently.
Next, we need to create a JSON file that will function as our temporary "database":
users.json
in the root of the project .
const usersFilePath = path.join(__dirname, 'users.json');
[ { { " id": 1, " name": "User 1", " email": "[email protected]" }, { " id": 2, " name": "User 2", " email": "[email protected]" }]
This configuration will allow us to access and manipulate user data stored locally, simulating the operations we would perform with a real database.
Once our project is configured to work with local files, we can implement our first endpoint: GET /users.
app.get('/users', (req, res) => { fs.readFile(usersFilePath, 'utf8', (error, data) => { if (error) { return res.status(500).json({ error: "Error with data connection" }); }
const users = JSON.parse(data); res.json(users); });});
Let's analyze this code step by step:
app.get()
to define a route that responds to HTTP GET requests./users
will be the entry point to get the list of users.fs.readFile()
to read the content of the JSON fileIt is crucial to implement proper error handling to provide useful information to the client when something goes wrong. In this case, we return a status code 500 (Server Error) along with a descriptive message.
To verify that our endpoint is working properly, we can use different tools:
http://localhost:PUERTO/users
In Postman, we can:
The advantage of using Postman is that we can organize all our API requests and easily share them with other team members, which facilitates collaboration and testing.
The structure we are implementing now, while using local files, is designed to ease the transition to a database in the future. The basic logic will remain similar:
This separation of concerns allows us to modify the data source without significantly changing the logic of our API. When we are ready to migrate to a database, we will only need to replace the file operations with database queries.
Furthermore, by organizing our code in this way, we are following good development practices that make our code more maintainable and scalable in the long run.
Implementing the GET method is just the first step in creating a complete RESTful API. In the next sections, we will explore how to implement other HTTP methods such as POST to create new users in our local "database".
Have you implemented RESTful APIs before, and what challenges have you faced when working with Node.js and Express? Share your experiences in the comments and continue learning about backend development.
Contributions 1
Questions 0
Want to see more contributions, questions and answers from the community?