How data flows in backend calls to your PostgreSQL Database.

A step by step explanation of how to retrieve data from a REST API connected to a database.

How does data flow when retrieving data from your database? It is a question, I get asked a lot, In many different ways, and I have given many different explanations.

They are 6 steps

Step 1: Make a call to your endpoint.

This step can use axios or a superagent module, fetch or the classic xhr.

Step 2: Hits your endpoint and runs your method on controller file, or right in that endpoint.

If you have a method set to that endpoint, just define the method within the endpoint, doesn’t really matter. It will hit that method and run the method.

Step 3: If you have a variable set to the database instance or have straight ran with the req.app.get.

It will run the sql file, if successful it will run the sql file.

Step 4: Returns sql data, if they are select statement or returning clauses.

It will return data from the sql file if they are select statements. The returned data will always will be in form of an array, and will be passed in the argument when the promise resolves or the .then. NOTE: You can name the argument anything you want, it will still return the same data.

dbInstance.get_products().then(skittles => {
})
OR
dbInstance.get_products().then(products => {
})
Same thing.

Step 5: Return the data to the front end using the res.send( ) or res.json({})

Both will return data, the only difference that .json({}) will add a object to the data being returned to the frontend.

Step 6: Get the data, and setState.

If you are using axios will be in the res.data. I would recommend console logging data to make sure you are getting the right data. Also for every single promise always have a .catch, it is very useful for catching errors.

Here is a diagram explaining it. This is a very simple article, its not that complex. Issues I had in the past was connecting to a database. But once connected to the database performing crud would be much easier, and can make real applications with secure data.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store