Tuesday 14 March 2017

Am I doing this REST API correct ? How would you do it

I know there are many different ways of doing things so I am asking if the way I am doing it is okay/the right way to do it.I am using express and sequelize.So I have two controllers folders. the API folder, and the home page folder.In the api folder, I have simple app.get that lead to the link '/api/users' and '/api/users/:id'. The code (roughly) looks like so.app.get('/api/users/', function (req, res) { db.users.findAll().then(function (users) { res.json(users); }); }); app.get('/api/users/:id', function (req, res){ db.users.findById(req.params.id).then(function(user){ if(user === null){ res.status(404).send({error: 'User does not exist.'}); return; } res.json(user); }); }); Pretty neat, so when I go to localhost:4000/api/users I get a list of all the users in json form! Now comes to the client side which is where I am having trouble.There are many ways in which I can approach this so I will provide maybe two ideas I have.The Problem: For an example, I want my home page to display all the users we created in a nice html/css site....How do I go about retrieving this data for the front end/ client side ? This is what I currently have.app.get('/', function (req, res) { db.users.findAll().then(function (users) { res.render('pages/index', {usersObj: users}); }); }); But...I am essentially doing the same thing for the 'api/users' ... no ? Is there a way for me to call the api link instead and take advangate of what I just made?I guess I could just write front end ajax to retrieve the data from the database data from the api url I created (which contains the database data). But what happens if I want to display 5 users instead...surely the 'api/users' can't handle retrieving 5 users as the backend only displays all of them.... I guess I could manipulate the the ajax to cut off and keep only the first 5 array elements from the 'api/users' response.Overall question: What's the best way for the front end / client side to get data from my custom 'api' that I created ? I see a lot of tutorials covering API but they don't seem to go into the client side... should I retrieve the data via the backend ? Or the front end with ajax ? Or am I approaching this the wrong way... thanks !

Submitted March 14, 2017 at 12:15PM by HappyZombies

No comments:

Post a Comment