Create a Simple API

See Related Information below for other tutorials for creating APIs.

This tutorial is based on Maximillian Schwarzmüller's Creating a REST API with Node.js starting with Part 2:

  1. Planning & First Steps
  2. Adding More Routes to the API | Creating a REST API with Node.js
  3. Handling Errors & Improving the Project Setup | Creating a REST API with Node.js

First Steps

  1. If you are using Windows, open PowerShell, and go to C:\ or whatever the root directory is on your computer.
  2. Download node.js
  3. To ensure that the install works, run:
    node -v
    npm -v
  4. Create a directory for this API:
    mkdir node-rest-shop
  5. Enter that new directory:
    cd node-rest-shop
  6. Next, use this command:
    npm init
  7. init asks you a series of questions; here are some examples:
    package name: something like rest-shop
    version: just press Enter
    description: something like node.js RESTful API
    entry point: just accept (index.js)
    test command: just press Enter
    git repository: just press Enter
    keywords: api restful node
    author: use your name
    license: just press Enter for (ISC)
    Press Enter for Is this okay?
  8. In your API directory, open package.json just for a look.
  9. Run npm install --save express
  10. Start creating server by starting a file named server.js. In this file:
    const http = require('http');
    const express = require('express');
    const app = express();
    const port = process.env.PORT || 3000;
    const server = http.createServer(app);
    
    server.listen(port);
    
    app.use((req, res, next) => 
    { 
        res.status(200).json({ message: 'It works!' })
    }); 
    module.exports = app;
  11. Next, create app.js containing these lines:
    const express = require('express');
    const app = express();
    const productRoutes = require('./api/routes/products');
    module.exports = app;
    
  12. At same command line in the node-rest-shop folder, enter node server.js
  13. To see if all this works, open a browser and enter this works: localhost:3000
    Expect to see message "It works!"

Note: Max makes changes to these two files in the next video. They work here for localhost:3000 (see max_api1.zip)

Test the Code in Postman

Postman provides an easy way to test various API requests.

  1. To download Postman,go to https://www.getpostman.com
  2. Select your OS, and download.
  3. Click Install
  4. Set up an account.
  5. Click Request
  6. Select POST and enter localhost:3000
  7. Click Send
  8. Click Raw, Headers, etc.

Add more routes

To continue:

  1. Next, create a subdirectory called api and within that subdirectory create another called routes. (The routes folder is an end point). In that subsubdirectory, create products.js with these these lines:
    const express = require('express');
    const router = express.Router();
    
    router.get('/', (req, res, next) => {
        res.status(200).json({
            message: 'Handling GET requests to /products'
        });
    });
    
    router.post('/', (req, res, next) => {
        res.status(200).json({
            message: 'Handling POST requests to /products'
        });
    });
    
    router.get('/:productID', (req, res, next) => {
        const id = req.params.productId;
        if (id === 'special') {
            res.status(200).json({
                message: 'You found the spcial ID',
                id: id
            });
        } else {
            res.status(200).json({
                message: 'You passed an ID'
            });
        };
    }); 
    module.exports = router;
    
  2. Now to test this out, you'll first need to Ctrl+C to stop the server if it is running and then re-issue node server.js. This is because we've made some changes to server.js.
  3. Back in Postman, enter this command localhost:3000/products/123 with 123 being the ID.
  4. To add order-related routes, start orders.js in the routes subdirectory. Enter these lines in orders.js:
    const express = require('express');
    const app = express();
    
    const productRoutes = require('./api/routes/products');
    const orderRoutes = require('./api/routes/orders');
    
    app.use('/products', productRoutes);
    app.use('/orders', orderRoutes);
    
    module.exports = app;
    
  5. Once again, restart the server with the node server.js command.
  6. Select GET with localhost:3000/orders then Send; should see Orders were fetched

    Select POST with localhost:3000/orders then Send; should see Order was created

    Select GET with localhost:3000/orderssomeorderid then Send; should see Order details . . . orderId: someorder id

    Select DELETE with localhost:3000/orders then Send; should see Order deleted

Automatically Restart the Server

It's a drag having to restart the server with that node server.js command all the time. A package called nodemon does the restart automatically every time to change something in the files.

  1. In the root directory of this project (called here node-rest-shop), enter npm install --save-dev nodemon
  2. After that installs, in package.json, add a comma to this line so that it looks like this: "test": "echo "Error: no test specified" && exit 1",
  3. On the next line, enter "start": "nodemon server.js" (including the quotation marks).
  4. Now at the command line in the root directory of this project, enter npm start. You'll see output in the Visual Studio Code terminal window like this:
  5. explanation of this image will be supplied

Notice that every time you make any change to any of your API project files, another one of the lines [nodemon] starting `node server.js` is added to the terminal window.

View Logging Messages and Handle Errors

You'll want to see detailed error and status messages for this API project. These will appear in the terminal if you run an IDE like Visual Studio Code

  1. To see logging messages, install morgan: npm install --save morgan.
  2. Open app.js and just below the const app line, add const morgan = require('morgan');
  3. Still in app.js, just below the const orderRoutes line, add app.use(morgan('dev')) ;
  4. Note that lines coding for morgan are handled above.

Related Information

Build your first Hello Mule application. Simple API, mulesoft

Create A Paginated API With Node.js - Complete Tutorial promo?

How to Create a Sports Betting Application with Python (using TheRundown API)

REST API Crash Course - Introduction + Full Python API Tutorial

The REST API Handbook – How to Build, Test, Consume, and Document REST APIs

Use Django REST Framework to Create Web APIs

Create An API: CORS, SPA / Client-Side Routing Explanation

REST API Design Best Practices Handbook – How to Build a REST API with JavaScript, Node.js, and Express.js fcc

Use React and APIs to Build a Weather App fcc

How to build a REST API with Node js & Express

Create an Industry Level REST API Using .NET fcc

An awesome guide on how to build RESTful APIs with ASP.NET Core

Tutorial: Create a minimal API with ASP.NET Core ms

Information and programs provided by admin@mcmassociates.io.