DEV Community

Discussion on: How do you implement REST in an MVC application?

Collapse
 
joseluisrnp profile image
José Luis Recio • Edited

Backend:

  • Models: It connect with database and we use in controllers. (Intermediary between database and controllers)
  • Controllers: It does our logic for each endpoint. (Intermediary between Models and Routes)
  • Routes: It has a call route method (example: GET /api/users) and the controller to execute when it is call (Intermediary between controllers and Frontend)

Frontend:

  • Simply call to your api endpoint with fetch, axios or your library selected)

Example flow with fetch and express in backend:

//Frontend
const getUsers = async () => {
  const response = await fetch('https://yourapi.com/api/users');
  const data = await response.json();
  return data; //Our users
}

//Backend
  //./routes/
  //If we recieve a call to /api/users we call to usersController
app.get('/api/users', usersController)

  // ./controllers
const usersControllers = () => {
  const users = modelUser.get();//Ey model give me users from database
  //Do logic with our users and return it
}

  // ./models
const modelUser = {
  get: () => databaseCall('SELECT * FROM users'); //Ey database give me users
}

Enter fullscreen mode Exit fullscreen mode

In this way:
Do you change de database? Only modify the model
Do you change your logic? Only modify the controller
Do you change your routing? Only modify the route

Collapse
 
hexparadus profile image
hex-paradus

This was a really good explanation! Thank you.