Simple Express API

by | Aug 6, 2023 | Tech

In this code, I built a simple Node application that serves as an API to retrieve data from a MySQL database. The application is using the Express.js framework and the MySQL library to achieve this.

First, I imported the required modules: mysql for database connectivity and express to create the web server.

I created an instance of the Express application and set the port variable to 3000. This means the server will listen on port 3000 when it starts.

Next, I created a MySQL pool that allows us to manage multiple database connections efficiently. The pool is configured with the necessary credentials to connect to the database hosted on Amazon RDS.

Now, defined two routes for our API:

  1. /api/devices/:location: This route handles GET requests and expects a :location parameter in the URL. The function retrieves data from the database using the pool’s query method. It executes a SQL query to fetch all rows from the objects_view table where the station_name column matches the provided location, and the object_type column is set to ‘device’. If there’s an error during the query, it responds with a 500 status code and an error message. Otherwise, it returns the query results as a JSON response.
  2. /api/points/:location/:parent: This route also handles GET requests and expects two parameters: :location and :parent in the URL. Similarly, it queries the objects_view table to fetch rows where station_name matches the provided location, and the parent_device matches the provided parent. If there’s an error during the query, it sends a 500 status code and an error message. Otherwise, it returns the query results as a JSON response.

With these routes defined, the web server is ready to handle incoming requests to the specified endpoints. When the server starts, it logs a message indicating that it’s listening on the specified port.

This API is used to retrieve data from the database based on the provided location or location and parent parameters in the URL. The data is returned in JSON format, making it easy to process and use the information.

For this Project and more like this Visit my Github

More Like This……

Adding Custom Attributes to User Accounts in Active Directory

Adding Custom Attributes to User Accounts in Active Directory

I'd like to dive into a subject that many IT professionals find themselves dabbling in at some point: customizing user accounts in Active Directory by adding unique attributes. This is an awesome feature in AD, allowing us to store additional, specific information...

Detecting Failed Login Attempts with PowerShell

Detecting Failed Login Attempts with PowerShell

In my experience as a tech enthusiast and system administrator, I've come to realize the importance of staying ahead of cybersecurity threats. It's a constant battle to safeguard our customers' sensitive data and systems from potential breaches. One of the common ways...