Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 2400

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 61k
Author
Asked: November 26, 20242024-11-26T05:04:09+00:00 2024-11-26T05:04:09+00:00

Simple Node and Express REST API

  • 61k

Learn by example how to make a simple API that has two endpoints.

What we will make in this tutorial:

  • simple server running locally on your computer
  • using mocked data for simplicity
  • creating endpoints that we will call to change our data
  • use Postman to query our endpoints

Tutorial on YouTube:

The Code:

const express = require("express"); const bodyParser = require("body-parser");  const app = express(); app.use(bodyParser.json()); const port = 3001;  const customers = [   { firstName: "John", lastName: "Smith" },   { firstName: "Harry", lastName: "Potter" },   { firstName: "Jack", lastName: "Sparrow" }, ];  app.get("/customerlist", (req, res) => {   res.send(customers); });  app.post("/customer", (req, res) => {   console.log("req.body: ", req.body);   const newCustomer = req.body;   customers.push(newCustomer);   res.send("Customer added."); });  app.listen(port, () => {   console.log(`Example app listening at http://localhost: ${port}`); });  
Enter fullscreen mode Exit fullscreen mode

So let's first talk about the data we will be working with. Its simply an array of objects, with a couple of key/value pairs. First and last name. Feel free to make as many creative additions as you'd like here.
The data:

const customers = [   { firstName: "John", lastName: "Smith" },   { firstName: "Harry", lastName: "Potter" },   { firstName: "Jack", lastName: "Sparrow" }, ]; 
Enter fullscreen mode Exit fullscreen mode

Now let's just take a look at what is the essential part of our server. The boilerplate code that needs to be there for our server to run.
Boilerplate code for the server to run:

const express = require("express"); const bodyParser = require("body-parser");  const app = express(); app.use(bodyParser.json()); const port = 3001;  app.listen(port, () => {   console.log(`Example app listening at http://localhost: ${port}`); 
Enter fullscreen mode Exit fullscreen mode

So basically we need to import express and body parser. Express because it is the framework we use on top of nodejs. Bodyparser so that we can do POST requests and change our data. We set a port so it is open for running queries through it in Postman, and we say listen to that port. Most of this is done with the app variable. Which has some important properties on it, like use and listen.

What we then do is add our endpoints.

What are endpoints?

Endpoints are dedicated spaces under your projects URL that you can visit with a certain request, be it a GET- or a POST-request, and have something happen. The most useful thing to have happen is manipulating the data in a logical way. We like to read, write, update and delete our data, depending on the scenario. These actions corresponds to doing CRUD operations within our RESTful API. And what does all that mean? A RESTful API is a backend service designed in a way that follows a certain pattern we call REST. It's not that easy to get a straight answer to what exactly that entails, when asking google, and it gets pretty technical. CRUD operations on the other hand is more straight forward. Its and acronym which stands for Create, Read, Update and Delete. Doing those operations are usually speaking generally, what you want your API to be able to do.

So back to endpoint. If you create a GET endpoint in your API, it's purpose is usually to get data, or Read data from the database. In the same way, a POST route usually creates new data in the database when called. The thing is you can't just visit the post route in your browser and expect it to get called. You need to explicitly make it a POST request. That's why we use Postman!

image

So our first endpoint just responds with our data, where res stands for response. And the thing that is sent back to us is the customer list called customers. So when calling this endpoint in Postman we would get the list back as a response.

app.get("/customerlist", (req, res) => {   res.send(customers); }); 
Enter fullscreen mode Exit fullscreen mode

image

Lastly we have the POST route which adds one customer to the customer list. Because this is just mocked data we can use simple array manipulation here with customers.push(newCustomer) to add a new customer to the object array.

app.post("/customer", (req, res) => {   console.log("req.body: ", req.body);   const newCustomer = req.body;   customers.push(newCustomer);   res.send("Customer added."); }); 
Enter fullscreen mode Exit fullscreen mode

Conclusion

This is probably one of the easier APIs you can make with Node and Express, but it covers the most basics concepts. And with everything being in the same file I was hoping it would be easier to connect the dots. A natural next step here could be to expand the endpoints to include Update and Delete requests, so you can update and delete objects in the array. You could also change the mocked data to go directly to a database.

I hope you got something from this. Later I'll maybe write an article that does basically the same just that it is connected to Mongodb Atlas.

Cheers!

Follow and support me:

I am especially grateful for subscriptions to my YouTube channel. And if you want to follow me on Twitter, or just give some feedback that's awesome too!

📺 YouTube

🐧 Twitter

I try to get out new web dev content on Youtube every week, and sometimes I write articles like this one.
Hope you enjoy!

beginnersnodetutorialwebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 2k
  • Popular
  • Answers
  • Author

    ES6 - A beginners guide - Template Literals

    • 0 Answers
  • Author

    Understanding Higher Order Functions in JavaScript.

    • 0 Answers
  • Author

    Build a custom video chat app with Daily and Vue.js

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.