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
12 Hrs
40 Min
4 Seg
Curso de Backend con ExpressJS

Curso de Backend con ExpressJS

Oscar Barajas Tavares

Oscar Barajas Tavares

Solicitudes GET

8/30
Resources

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.

How to configure a Node.js project to work with local files?

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":

  1. Create a file named users.json in the root of the project .
  2. Define the path to this file using the path module:
const usersFilePath = path.join(__dirname, 'users.json');
  1. Structure the JSON file with some test data:
[ { { " 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.

How to implement the GET method to obtain users?

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:

  1. We use app.get() to define a route that responds to HTTP GET requests.
  2. The path /users will be the entry point to get the list of users.
  3. Inside the callback, we use fs.readFile() to read the content of the JSON file
  4. We include error handling to respond appropriately if any problems occur
  5. If everything works correctly, we parse the JSON data and send it as a response

It 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.

Testing our endpoint

To verify that our endpoint is working properly, we can use different tools:

  1. Web browser: Being a GET request, we can simply browse to http://localhost:PUERTO/users
  2. Postman: A more robust tool that allows us to document and organize our API requests.

In Postman, we can:

  • Create a new collection (e.g., "API Users")
  • Add a new GET request to the URL of our endpoint
  • Execute the request and verify the response
  • Save the request for future use

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.

Why is it important to structure your API correctly?

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:

  1. Receive an HTTP request.
  2. Fetch data (either from a local file or a database)
  3. Process that data as needed
  4. Send an appropriate response

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

Sort by:

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

JSON que usamos:\[ { "id": 1, "name": "John Doe", "email": "[email protected]" }, { "id": 2, "name": "Jenny Smith", "email": "[email protected]" }] ```js [ { "id": 1, "name": "John Doe", "email": "[email protected]" }, { "id": 2, "name": "Jenny Smith", "email": "[email protected]" } ] ```