I'm working on the frontend part of some REST API (link, json validation and in generale controlling) I'm trying to figure out how it works in the backhand, there should be a database I guess and each API call correspond to a specific query?
could you suggest me guide on how such implementation are usually build? I'm only finding formal guide on how to shape url for rest API
thanks
It is a quite generale / cultural question, not technical
CodePudding user response:
There's no standard way, the point of a protocol like HTTP (what REST is based on) is to decouple this kind of details and leave the server implementor to be free of doing it however it wants.
There are a lot of different ways and listing them all is very hard.
For a simple service what you said is true, for more complex scenario behind a REST endpoint there could be a service doing calls to other services and aggregating their responses into the json you see.
CodePudding user response:
You would usually have a single endpoint do a single task but you could also do anything you want with the data provided from the user. You could carry out regex validations, store it inside a database, send it to another API, extract data out of it, and plenty of other things. Here is an example I wrote in Node.js:
const signup_post = async (req, res) => {
const { email, password, username } = req.body;
try {
const user = await User.create({ email, password, username });
const token = createToken(user._id);
res.cookie('jwt', token, { httpOnly: true, maxAge: maxAge * 1000 });
res.status(201).json({ user: user._id });
}
catch(err) {
const errors = handleErrors(err);
res.status(400).json({ errors });
}
}
This example code, we are taking the user-provided data, making a new entry in the database with a pre-defined schema, creating a JWT token and attaching it to a cookie, and sending the cookie back to the client. This is one way to handle authentication- and as long as the client has this cookie, they will stay logged in. We are also handling any errors and validating the user-provided data to make sure it fits our database schema.