{"id":4017,"date":"2023-11-04T23:14:00","date_gmt":"2023-11-04T23:14:00","guid":{"rendered":"http:\/\/localhost:10003\/building-restful-apis-with-express-js\/"},"modified":"2023-11-05T05:48:23","modified_gmt":"2023-11-05T05:48:23","slug":"building-restful-apis-with-express-js","status":"publish","type":"post","link":"http:\/\/localhost:10003\/building-restful-apis-with-express-js\/","title":{"rendered":"Building Restful APIs with Express.js"},"content":{"rendered":"

Introduction<\/h2>\n

Express.js is a popular Node.js web framework that simplifies the development of web applications. It is used to create server-side applications and APIs that respond to client requests. Building a Restful API with Express.js is straightforward and helps you build scalable, modular and maintainable applications.<\/p>\n

This tutorial will guide you through the process of building Restful APIs with Express.js. You will learn the fundamentals of RESTful architecture, how to create RESTful routes in Express.js and how to handle requests and responses.<\/p>\n

Prerequisites<\/h2>\n

Before getting started, you will need to have Node.js and npm installed on your machine. You can download the latest version of Node.js from the official website https:\/\/nodejs.org\/<\/a>.<\/p>\n

Creating a New Project<\/h2>\n

First, create a new directory for your project and navigate to that directory using the terminal. Next, initialize a new Node.js project using the following command:<\/p>\n

npm init -y\n<\/code><\/pre>\n

This command will create a new package.json<\/code> file in the current directory with default values.<\/p>\n

Next, install the express<\/code> package using the following command:<\/p>\n

npm install express\n<\/code><\/pre>\n

This command installs the latest version of the express<\/code> package and adds it to the dependencies<\/code> section of the package.json<\/code> file.<\/p>\n

Creating a Server<\/h2>\n

Now that you have set up your project, you can begin building your Restful API with Express.js. Start by creating an index.js<\/code> file in the root directory of your project. This file will be the entry point of your application.<\/p>\n

Open the index.js<\/code> file in your favorite code editor and add the following code:<\/p>\n

const express = require('express');\n\nconst app = express();\n\nconst port = process.env.PORT || 3000;\n\napp.listen(port, () => {\n  console.log(`Listening on port ${port}...`);\n});\n<\/code><\/pre>\n

In this code, you first import the express<\/code> module. You then create a new express<\/code> application by calling the express()<\/code> function. Finally, you specify the port that your server will listen on and start the server by calling the listen()<\/code> method.<\/p>\n

To run your application, open the terminal in the root directory of your project and run the following command:<\/p>\n

node index.js\n<\/code><\/pre>\n

This will start your server on the specified port. You can navigate to http:\/\/localhost:3000<\/a> in your web browser to check if your server is running correctly.<\/p>\n

Routing<\/h2>\n

Routing is a mechanism in Express.js that allows us to define the structure of our API. Express.js provides a way to define routes for different HTTP requests like GET, POST, PUT and DELETE. Each request method is associated with a specific function that is called when a request is received.<\/p>\n

Defining Routes<\/h3>\n

To define a new route for your API, add the following code to your index.js<\/code> file:<\/p>\n

app.get('\/', (req, res) => {\n  res.send('Hello World!');\n});\n<\/code><\/pre>\n

In this code, you define a new route for the root URL (‘\/’). This route will be used to handle GET requests. When a GET request is received for the root URL, the callback function (req, res)<\/code> is called. In this callback function, you send the string ‘Hello world!’ as the response to the client.<\/p>\n

Route Parameters<\/h3>\n

Route parameters are used to extract data from the URL and pass it as an argument to the callback function. To define a route parameter, start the parameter name with a colon(:).<\/p>\n

app.get('\/users\/:id', (req, res) => {\n  const id = req.params.id;\n  res.send(`User ID: ${id}`);\n});\n<\/code><\/pre>\n

In this code, you define a route parameter :id<\/code>. You then extract the value of this parameter using req.params.id<\/code>. Finally, you send the extracted value as a response to the client.<\/p>\n

Route Methods<\/h3>\n

Express.js provides HTTP methods for each route that can be specified using the app.METHOD()<\/code> functions, where METHOD<\/code> is the HTTP method of the request that the route handles.<\/p>\n

app.post('\/users', (req, res) => {\n  const user = {\n    name: req.body.name,\n    email: req.body.email\n  };\n  \/\/ Save the user to the database\n  res.send(user);\n});\n<\/code><\/pre>\n

In this code, you define a new route for the URL ‘\/users’. This route will be used to handle POST requests. When a POST request is received for the ‘\/users’ URL, the callback function (req, res)<\/code> is called. In this callback function, you extract the name and email fields from the request body and save them to the database. You then send the saved user as a response to the client.<\/p>\n

Route Chaining<\/h3>\n

Route chaining is a mechanism in Express.js that allows us to chain multiple HTTP methods on a single route.<\/p>\n

app.route('\/users\/:id')\n  .get((req, res) => {\n    const id = req.params.id;\n    \/\/ Get the user with the ID from the database\n    res.send(user);\n  })\n  .put((req, res) => {\n    const id = req.params.id;\n    const user = {\n      name: req.body.name,\n      email: req.body.email\n    };\n    \/\/ Update the user with the ID in the database\n    res.send(user);\n  })\n  .delete((req, res) => {\n    const id = req.params.id;\n    \/\/ Delete the user with the ID from the database\n    res.send('User deleted');\n  });\n<\/code><\/pre>\n

In this code, you define a new route for the URL ‘\/users\/:id’. You then chain multiple HTTP methods on this route to handle GET, PUT and DELETE requests. When a GET request is received for the ‘\/users\/:id’ URL, the callback function (req, res)<\/code> is called. In this callback function, you extract the user ID from the URL and retrieve the user with this ID from the database. You then send the retrieved user as a response to the client. Similarly, you handle PUT and DELETE requests by extracting the user ID from the URL, updating or deleting the user from the database and sending an appropriate response to the client.<\/p>\n

Middleware<\/h2>\n

Middleware is a function that sits between the request and response cycle of a server and performs some action on the request before it reaches the response. Middleware can be used for a wide variety of purposes like authentication, logging, error handling, etc.<\/p>\n

Creating Middleware<\/h3>\n

To create middleware, use the app.use()<\/code> method. This method takes a callback function as an argument that receives the request and response objects as arguments.<\/p>\n

app.use((req, res, next) => {\n  console.log('Middleware called...');\n  next();\n});\n<\/code><\/pre>\n

In this code, you define a new middleware function that logs a message to the console. The next()<\/code> function is called to pass control to the next middleware in the chain.<\/p>\n

Using Middleware in Routes<\/h3>\n

Middleware can be used in specific routes by passing them as arguments to the app.METHOD()<\/code> function.<\/p>\n

app.get('\/users', (req, res, next) => {\n  console.log('Middleware called...');\n  next();\n}, (req, res) => {\n  res.send('Users list');\n});\n<\/code><\/pre>\n

In this code, you define a new route for the URL ‘\/users’. You then pass a middleware function as the first argument to the app.get()<\/code> function. This middleware function logs a message to the console. You then define the callback function (req, res)<\/code> that sends the string ‘Users list’ as the response.<\/p>\n

Conclusion<\/h2>\n

In this tutorial, you learned how to build Restful APIs with Express.js. You learned the fundamentals of RESTful architecture, how to create RESTful routes in Express.js and how to handle requests and responses. You also learned how to use middleware in your application for various purposes like authentication, logging, error handling, etc.<\/p>\n

Express.js is a versatile and powerful web framework that simplifies the development of web applications and APIs. It provides a wide range of features that make it easy to create scalable, modular and maintainable applications. With the knowledge you gained from this tutorial, you can start building your own Restful APIs using Express.js.<\/p>\n","protected":false},"excerpt":{"rendered":"

Introduction Express.js is a popular Node.js web framework that simplifies the development of web applications. It is used to create server-side applications and APIs that respond to client requests. Building a Restful API with Express.js is straightforward and helps you build scalable, modular and maintainable applications. This tutorial will guide Continue Reading<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_import_markdown_pro_load_document_selector":0,"_import_markdown_pro_submit_text_textarea":"","footnotes":""},"categories":[1],"tags":[407,455,851,49,850],"yoast_head":"\nBuilding Restful APIs with Express.js - Pantherax Blogs<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"http:\/\/localhost:10003\/building-restful-apis-with-express-js\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Building Restful APIs with Express.js\" \/>\n<meta property=\"og:description\" content=\"Introduction Express.js is a popular Node.js web framework that simplifies the development of web applications. It is used to create server-side applications and APIs that respond to client requests. Building a Restful API with Express.js is straightforward and helps you build scalable, modular and maintainable applications. This tutorial will guide Continue Reading\" \/>\n<meta property=\"og:url\" content=\"http:\/\/localhost:10003\/building-restful-apis-with-express-js\/\" \/>\n<meta property=\"og:site_name\" content=\"Pantherax Blogs\" \/>\n<meta property=\"article:published_time\" content=\"2023-11-04T23:14:00+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2023-11-05T05:48:23+00:00\" \/>\n<meta name=\"author\" content=\"Panther\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Panther\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"6 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\n\t \"@context\": \"https:\/\/schema.org\",\n\t \"@graph\": [\n\t {\n\t \"@type\": \"Article\",\n\t \"@id\": \"http:\/\/localhost:10003\/building-restful-apis-with-express-js\/#article\",\n\t \"isPartOf\": {\n\t \"@id\": \"http:\/\/localhost:10003\/building-restful-apis-with-express-js\/\"\n\t },\n\t \"author\": {\n\t \"name\": \"Panther\",\n\t \"@id\": \"http:\/\/localhost:10003\/#\/schema\/person\/b63d816f4964b163e53cbbcffaa0f3d7\"\n\t },\n\t \"headline\": \"Building Restful APIs with Express.js\",\n\t \"datePublished\": \"2023-11-04T23:14:00+00:00\",\n\t \"dateModified\": \"2023-11-05T05:48:23+00:00\",\n\t \"mainEntityOfPage\": {\n\t \"@id\": \"http:\/\/localhost:10003\/building-restful-apis-with-express-js\/\"\n\t },\n\t \"wordCount\": 1029,\n\t \"publisher\": {\n\t \"@id\": \"http:\/\/localhost:10003\/#organization\"\n\t },\n\t \"keywords\": [\n\t \"\\\"API development\\\"\",\n\t \"\\\"express.js\\\"\",\n\t \"\\\"RESTful architecture\\\"\",\n\t \"\\\"Web development\\\"\",\n\t \"[\\\"Building Restful APIs\\\"\"\n\t ],\n\t \"inLanguage\": \"en-US\"\n\t },\n\t {\n\t \"@type\": \"WebPage\",\n\t \"@id\": \"http:\/\/localhost:10003\/building-restful-apis-with-express-js\/\",\n\t \"url\": \"http:\/\/localhost:10003\/building-restful-apis-with-express-js\/\",\n\t \"name\": \"Building Restful APIs with Express.js - Pantherax Blogs\",\n\t \"isPartOf\": {\n\t \"@id\": \"http:\/\/localhost:10003\/#website\"\n\t },\n\t \"datePublished\": \"2023-11-04T23:14:00+00:00\",\n\t \"dateModified\": \"2023-11-05T05:48:23+00:00\",\n\t \"breadcrumb\": {\n\t \"@id\": \"http:\/\/localhost:10003\/building-restful-apis-with-express-js\/#breadcrumb\"\n\t },\n\t \"inLanguage\": \"en-US\",\n\t \"potentialAction\": [\n\t {\n\t \"@type\": \"ReadAction\",\n\t \"target\": [\n\t \"http:\/\/localhost:10003\/building-restful-apis-with-express-js\/\"\n\t ]\n\t }\n\t ]\n\t },\n\t {\n\t \"@type\": \"BreadcrumbList\",\n\t \"@id\": \"http:\/\/localhost:10003\/building-restful-apis-with-express-js\/#breadcrumb\",\n\t \"itemListElement\": [\n\t {\n\t \"@type\": \"ListItem\",\n\t \"position\": 1,\n\t \"name\": \"Home\",\n\t \"item\": \"http:\/\/localhost:10003\/\"\n\t },\n\t {\n\t \"@type\": \"ListItem\",\n\t \"position\": 2,\n\t \"name\": \"Building Restful APIs with Express.js\"\n\t }\n\t ]\n\t },\n\t {\n\t \"@type\": \"WebSite\",\n\t \"@id\": \"http:\/\/localhost:10003\/#website\",\n\t \"url\": \"http:\/\/localhost:10003\/\",\n\t \"name\": \"Pantherax Blogs\",\n\t \"description\": \"\",\n\t \"publisher\": {\n\t \"@id\": \"http:\/\/localhost:10003\/#organization\"\n\t },\n\t \"potentialAction\": [\n\t {\n\t \"@type\": \"SearchAction\",\n\t \"target\": {\n\t \"@type\": \"EntryPoint\",\n\t \"urlTemplate\": \"http:\/\/localhost:10003\/?s={search_term_string}\"\n\t },\n\t \"query-input\": \"required name=search_term_string\"\n\t }\n\t ],\n\t \"inLanguage\": \"en-US\"\n\t },\n\t {\n\t \"@type\": \"Organization\",\n\t \"@id\": \"http:\/\/localhost:10003\/#organization\",\n\t \"name\": \"Pantherax Blogs\",\n\t \"url\": \"http:\/\/localhost:10003\/\",\n\t \"logo\": {\n\t \"@type\": \"ImageObject\",\n\t \"inLanguage\": \"en-US\",\n\t \"@id\": \"http:\/\/localhost:10003\/#\/schema\/logo\/image\/\",\n\t \"url\": \"http:\/\/localhost:10003\/wp-content\/uploads\/2023\/11\/cropped-9e7721cb-2d62-4f72-ab7f-7d1d8db89226.jpeg\",\n\t \"contentUrl\": \"http:\/\/localhost:10003\/wp-content\/uploads\/2023\/11\/cropped-9e7721cb-2d62-4f72-ab7f-7d1d8db89226.jpeg\",\n\t \"width\": 1024,\n\t \"height\": 1024,\n\t \"caption\": \"Pantherax Blogs\"\n\t },\n\t \"image\": {\n\t \"@id\": \"http:\/\/localhost:10003\/#\/schema\/logo\/image\/\"\n\t }\n\t },\n\t {\n\t \"@type\": \"Person\",\n\t \"@id\": \"http:\/\/localhost:10003\/#\/schema\/person\/b63d816f4964b163e53cbbcffaa0f3d7\",\n\t \"name\": \"Panther\",\n\t \"image\": {\n\t \"@type\": \"ImageObject\",\n\t \"inLanguage\": \"en-US\",\n\t \"@id\": \"http:\/\/localhost:10003\/#\/schema\/person\/image\/\",\n\t \"url\": \"http:\/\/2.gravatar.com\/avatar\/b8c0eda5a49f8f31ec32d0a0f9d6f838?s=96&d=mm&r=g\",\n\t \"contentUrl\": \"http:\/\/2.gravatar.com\/avatar\/b8c0eda5a49f8f31ec32d0a0f9d6f838?s=96&d=mm&r=g\",\n\t \"caption\": \"Panther\"\n\t },\n\t \"sameAs\": [\n\t \"http:\/\/localhost:10003\"\n\t ],\n\t \"url\": \"http:\/\/localhost:10003\/author\/pepethefrog\/\"\n\t }\n\t ]\n\t}<\/script>\n<!-- \/ Yoast SEO Premium plugin. -->","yoast_head_json":{"title":"Building Restful APIs with Express.js - Pantherax Blogs","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"http:\/\/localhost:10003\/building-restful-apis-with-express-js\/","og_locale":"en_US","og_type":"article","og_title":"Building Restful APIs with Express.js","og_description":"Introduction Express.js is a popular Node.js web framework that simplifies the development of web applications. It is used to create server-side applications and APIs that respond to client requests. Building a Restful API with Express.js is straightforward and helps you build scalable, modular and maintainable applications. This tutorial will guide Continue Reading","og_url":"http:\/\/localhost:10003\/building-restful-apis-with-express-js\/","og_site_name":"Pantherax Blogs","article_published_time":"2023-11-04T23:14:00+00:00","article_modified_time":"2023-11-05T05:48:23+00:00","author":"Panther","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Panther","Est. reading time":"6 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"http:\/\/localhost:10003\/building-restful-apis-with-express-js\/#article","isPartOf":{"@id":"http:\/\/localhost:10003\/building-restful-apis-with-express-js\/"},"author":{"name":"Panther","@id":"http:\/\/localhost:10003\/#\/schema\/person\/b63d816f4964b163e53cbbcffaa0f3d7"},"headline":"Building Restful APIs with Express.js","datePublished":"2023-11-04T23:14:00+00:00","dateModified":"2023-11-05T05:48:23+00:00","mainEntityOfPage":{"@id":"http:\/\/localhost:10003\/building-restful-apis-with-express-js\/"},"wordCount":1029,"publisher":{"@id":"http:\/\/localhost:10003\/#organization"},"keywords":["\"API development\"","\"express.js\"","\"RESTful architecture\"","\"Web development\"","[\"Building Restful APIs\""],"inLanguage":"en-US"},{"@type":"WebPage","@id":"http:\/\/localhost:10003\/building-restful-apis-with-express-js\/","url":"http:\/\/localhost:10003\/building-restful-apis-with-express-js\/","name":"Building Restful APIs with Express.js - Pantherax Blogs","isPartOf":{"@id":"http:\/\/localhost:10003\/#website"},"datePublished":"2023-11-04T23:14:00+00:00","dateModified":"2023-11-05T05:48:23+00:00","breadcrumb":{"@id":"http:\/\/localhost:10003\/building-restful-apis-with-express-js\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["http:\/\/localhost:10003\/building-restful-apis-with-express-js\/"]}]},{"@type":"BreadcrumbList","@id":"http:\/\/localhost:10003\/building-restful-apis-with-express-js\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"http:\/\/localhost:10003\/"},{"@type":"ListItem","position":2,"name":"Building Restful APIs with Express.js"}]},{"@type":"WebSite","@id":"http:\/\/localhost:10003\/#website","url":"http:\/\/localhost:10003\/","name":"Pantherax Blogs","description":"","publisher":{"@id":"http:\/\/localhost:10003\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"http:\/\/localhost:10003\/?s={search_term_string}"},"query-input":"required name=search_term_string"}],"inLanguage":"en-US"},{"@type":"Organization","@id":"http:\/\/localhost:10003\/#organization","name":"Pantherax Blogs","url":"http:\/\/localhost:10003\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"http:\/\/localhost:10003\/#\/schema\/logo\/image\/","url":"http:\/\/localhost:10003\/wp-content\/uploads\/2023\/11\/cropped-9e7721cb-2d62-4f72-ab7f-7d1d8db89226.jpeg","contentUrl":"http:\/\/localhost:10003\/wp-content\/uploads\/2023\/11\/cropped-9e7721cb-2d62-4f72-ab7f-7d1d8db89226.jpeg","width":1024,"height":1024,"caption":"Pantherax Blogs"},"image":{"@id":"http:\/\/localhost:10003\/#\/schema\/logo\/image\/"}},{"@type":"Person","@id":"http:\/\/localhost:10003\/#\/schema\/person\/b63d816f4964b163e53cbbcffaa0f3d7","name":"Panther","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"http:\/\/localhost:10003\/#\/schema\/person\/image\/","url":"http:\/\/2.gravatar.com\/avatar\/b8c0eda5a49f8f31ec32d0a0f9d6f838?s=96&d=mm&r=g","contentUrl":"http:\/\/2.gravatar.com\/avatar\/b8c0eda5a49f8f31ec32d0a0f9d6f838?s=96&d=mm&r=g","caption":"Panther"},"sameAs":["http:\/\/localhost:10003"],"url":"http:\/\/localhost:10003\/author\/pepethefrog\/"}]}},"jetpack_sharing_enabled":true,"jetpack_featured_media_url":"","_links":{"self":[{"href":"http:\/\/localhost:10003\/wp-json\/wp\/v2\/posts\/4017"}],"collection":[{"href":"http:\/\/localhost:10003\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/localhost:10003\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/localhost:10003\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/localhost:10003\/wp-json\/wp\/v2\/comments?post=4017"}],"version-history":[{"count":1,"href":"http:\/\/localhost:10003\/wp-json\/wp\/v2\/posts\/4017\/revisions"}],"predecessor-version":[{"id":4513,"href":"http:\/\/localhost:10003\/wp-json\/wp\/v2\/posts\/4017\/revisions\/4513"}],"wp:attachment":[{"href":"http:\/\/localhost:10003\/wp-json\/wp\/v2\/media?parent=4017"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/localhost:10003\/wp-json\/wp\/v2\/categories?post=4017"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/localhost:10003\/wp-json\/wp\/v2\/tags?post=4017"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}