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

Curso de Backend con ExpressJS

Oscar Barajas Tavares

Oscar Barajas Tavares

Appointments

28/30
Resources

Creating robust APIs requires careful planning of access points, especially when dealing with sensitive information such as medical appointments. In this article, we will explore how to implement an endpoint that allows authenticated users to view their appointment history, ensuring data security and privacy through authentication tokens.

How to implement an endpoint to list appointments of authenticated users?

When developing an API to manage appointments, it is critical to consider that a user could have multiple appointments in the system. Therefore, we need to create a specific entry point that allows each user to see only their own appointments, while keeping the information protected through authentication.

To implement this functionality, we will follow these steps:

  1. Configure the route on the main router
  2. Create the specific router for appointments
  3. Implement the controller
  4. Develop the service that interacts with the database
  5. Test the functionality with Postman

Configure routes for appointments access

The first step is to modify our main routing file to include the new resource. We need to add the appointments router and link it to the users route:

// In the main routing file (index.js)const appointmentsRouter = require('./appointments');
// We set up the route for users to access their appointmentsrouter.use('/users', appointmentsRouter);

Now, we must create the specific routing file for the appointments. This file will define the endpoints available to manage appointments:

// In the appointments.js fileconst router = require('express').Router();const appointmentController = require('../controllers/appointmentController');const authenticateToken = require('../middlewares/authenticate');
// Path to get a specific user's appointments// Protected with authentication middlewarerouter.get('/:id/appointments', authenticateToken, appointmentController.getUserAppointments);
module.exports = router;

It is crucial to note that we have included authentication middleware to ensure that only authenticated users can access this information. This protects data privacy and prevents unauthorized access.

Implementing the controller to manage appointments

The controller acts as an intermediary between routes and services. Its function is to receive the request, process it and return an appropriate response:

// In appointmentController.jsconst appointmentService = require('../services/appointmentService');
exports.getUserAppointments = async (req, res) => { try { const userId = req.params.id; const appointments = await appointmentService.getUserAppointments(userId);        
 res.json(appointments); } catch (error) { res.status(500).json({ message: 'Error getting appointment history' }); } } };

The controller extracts the user ID from the request parameters, calls the corresponding service and returns the results in JSON format. In case of error, it responds with a status code 500 and a descriptive message.

Developing the service to interact with the database

The service contains the business logic and communicates directly with the database. For our case, we will use Prisma as the ORM:

// In appointmentService.jsconst prisma = require('../config/prisma');
exports.getUserAppointments = async (userId) => { try { const appointments = await prisma.appointment.findMany({ where: { userId: parseInt(userId) }, include: { timeBlock: true } });        
 return appointments; } catch (error) { throw new Error('Error getting appointment history'); } } };

In this service:

  1. We use Prisma's findMany method to find all appointments associated with the user.
  2. We convert the userId to integer with parseInt
  3. We include the timeBlock relation to get additional information about each appointment
  4. We return the results or throw an error if something goes wrong

Testing with Postman

To verify that our endpoint is working correctly, we can use Postman:

  1. Import the test collection (available in the resources section).
  2. Make sure we have a valid authentication token
  3. Configure the GET request to the path /users/:id/appointments
  4. Include the token in the authorization header
  5. Send the request and verify the response

If everything is configured correctly, we should receive a JSON with the list of appointments for the specified user.

What security considerations should we take into account?

Security is a critical aspect when we develop APIs that handle personal information. Some important considerations are:

  • Mandatory authentication: As we have implemented, it is essential that only authenticated users can access their own appointments.
  • Permission validation: Although we did not implement it in this example, it would be advisable to verify that the authenticated user can only view their own appointments, not those of other users.
  • Data sanitization: We should always validate and sanitize the input data to prevent attacks such as SQL Injection.
  • Error handling: It is important to provide generic error messages to the client so as not to reveal internal system details.

How can we extend this functionality?

Once the basic endpoint for listing appointments is implemented, we can consider several enhancements:

  • Add pagination to handle large volumes of appointments.
  • Implement filters by date, status or appointment type.
  • Create additional endpoints to create, update or cancel appointments
  • Adding automatic notifications for appointment reminders

Implementing a robust appointment system requires attention to these details to provide a complete and secure experience for users.

Creating well-structured and secure APIs is fundamental to modern application development. By following REST design principles and applying good security practices, we can build reliable systems that protect our users' information while delivering full functionality. What other features do you consider important for an appointment management API? Share your ideas in the comments.

Contributions 0

Questions 0

Sort by:

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