Building the API - querying products
Once the database is set up and ready, you need to establish a connection with it. That's what you're going to do in this part of the course. Apart of that you will create backend API to get list of products and their descriptions.
Building the API#
Once your MongoDB instance is set up and fed with data, it's time to build an API that retrieves that data from the DB and serves it to the API consumer. Install the necessary dependencies:
Creating API - products endpoints#
Create a new file called api.ts (in the same directory as backend.ts) and add the following code:
The code above introduces the
express.Routing() object and sets up the middleware that you are going to use.
Connecting to the database#
To respond to an API client with a product list or user data, you first need to retrieve it from MongoDB. It's time to instantiate a connection with your MongoDB instance.
Add the following import statements to api.ts:
Set up a connection with the database:
Remember to replace the connection string and database name with your database-specific data.
Beware that database name which you provide in the
connection.db() method must match database name in your Atlasian account. Otherwise your program will fail silently - instead of returning data your API will respond with empty arrays and objects.
Because you are going to retrieve data from the database in multiple places in code, it's a good idea to add a helper function: