Simple read REST API with Express.js and Node.js
This short article shows how to create a simple read REST API with Node.js and Express.js.
Keywords: Node.js, Javascript, REST API, Express.js, Routing
DISCLAIMER: THE VIEWS AND OPINIONS EXPRESSED IN THIS ARTICLE ARE THOSE OF THE AUTHOR AND DO NOT REFLECT THE OFFICIAL POLICY OR POSITION OF THE EMPLOYER OF THE AUTHOR. THE ARTICLE IS NOT ENDORSED BY, DIRECTLY AFFILIATED WITH, MAINTAINED, AUTHORIZED, OR SPONSORED BY ANY CORPORATION OR ORGANIZATION. THE INFORMATION CONTAINED ON THIS ARTICLE IS INTENDED SOLELY TO PROVIDE GENERAL GUIDANCE ON MATTERS OF INTEREST FOR THE PERSONAL USE OF THE READER, WHO ACCEPTS FULL RESPONSIBILITY FOR ITS USE. ALTHOUGH THE AUTHOR HAS MADE EVERY EFFORT TO ENSURE THAT THE INFORMATION IN THIS ARTICLE WAS CORRECT AT THE TIME OF THE WRITING, THE AUTHOR DOES NOT ASSUME AND HEREBY DISCLAIM ANY LIABILITY TO ANY PARTY FOR ANY LOSS, DAMAGE, OR DISRUPTION CAUSED BY ERRORS OR OMISSIONS, WHETHER SUCH ERRORS OR OMISSIONS RESULT FROM NEGLIGENCE, ACCIDENT, OR ANY OTHER CAUSE.
Required knowledge
In order to understand this article you will need at least basic knowledge of
- Javascript
- Linux
- Node.js
- NPM
- Express.js
Initialization
We will use the folder name rest-api-express-node. The following commands will initialize this folder for us:
mkdir rest-api-express-node
cd rest-api-express-node
npm init -y
Install express.js
npm install --save express
The implementation of a simple web server looks like the following:
Routing
We need to specify routes for the web server. For this we will use another javascript file, routes.js
.
This implementation will return the string REST API call of '/'
every time the server root /
is accessed. We will need to include this file in our index.js
. The updated index.js
looks like the following:
Route parameters
For this tutorial we will use route parameter feature of express.js. For more information see the express.js documentation. We will implement the query of a todo entry by using the following URL: /todos/:todoid
. Route parameters are named URL segments that are used to capture the values specified at their position in the URL. In our example todoid
is a route parameter, When this kind of URL is accessed, we will return a dummy todo entry which we will generate on the fly. We need to modify routes.js
:
We can run the app:
node index.js
Enter http://localhost:3000/todos/123
to the URL in a browser.
This is just a very simple tutorial and test app to show the basics of using express routes and to return data in JSON format.
What are Future Plans for this Project?
- Enhance with further operations: query, create, delete, update
- Enhance with database access
The final project can be accessed on my Github page: