Sean Robertson

Sean Robertson

1579232472

How to Build a Simple REST API using Express

APIs are common means of communication between different software components. They provide a simple way to exchange data between two application. In our case, this will be between the browser and a database. In this post, we’re going to build a scalable REST API in Node using Express.

To keep things simple, we will go with the classical todo example. We will build an API to store, retrieve, modify and delete todo items. Each operation will be handled by a different HTTP request method. Our very first job will be to set up Express.

Setting Up Express

To make this tutorial concise and digestible, I will replace the database functionality with LocalStorage. Of course, we don’t have this in node so we will have to polyfill it. This means we will have two dependencies: express and node-localstorage. npm init -y your project and add these to your dependencies.

{
    "name": "express-api",
    "version": "1.0.0",
    "private": true,
    "scripts": {
        "start": "node server.js"
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "dependencies": {
        "express": "4.17.1",
        "node-localstorage": "2.1.5"
    }

I also replaced the default script withnode server.js; this is the file where we will set up the Express server. Create the server.js file in your root directory and add the following lines to it:

const express = require('express'),
      app     = express(),
      port    = process.env.PORT || 8080;

app.listen(port);

console.log(`API server is listening on port:${port}`);

We can start the webserver with app.listen passing in the port; either from the command line or defaulting to 8080. Not much is happening right now. If you open localhost:8080, you’ll see the server doesn’t return anything. So let’s change that and add some routes!

Creating Routes

For the routes, I’ve created a separate directory called routes and added an index.js. We’re going to have four different endpoints:

  • GET for getting all or a single todo item
  • POST for creating a new todo item
  • PUT for updating an existing todo item
  • DELETE for removing a specific todo item

This is how our routes/index.js will look like:

'use strict';

const routes = (app) => {
    const todo = require('../controllers/Todo');

    // Todo Route
    app.route('/todo/:id?/')
        .get(todo.get)
        .post(todo.create)
        .put(todo.update)
        .delete(todo.delete);
};

module.exports = routes;

routes will be a function that gets the express app as a parameter. The app variable exposes a route method which takes in an endpoint as a parameter. We can specify route params by using colons. By also adding a question mark at the end, we can tell express that this is only an optional param.

On route, we can chain different HTTP request methods. For every method, we will execute a different function. The methods are coming from an object defined in the controllers folder under Todo.js so that will be our next step.

But first, to actually tell Express to use these routes, go back to your server.js file and extend it with the following:

const express = require('express'),
      routes  = require('./routes/index'),
      app     = express(),
      port    = process.env.PORT || 8080;

routes(app);

app.listen(port);

console.log(`API server is listening on port:${port}`);

I’ve imported routes and passed the Express app to it. Now if you navigate to localhost:8080/todo it will call the todo.get method which we haven’t specified yet, so let’s do that right now.

Requests and Responses

If you haven’t already, create a controllers folder and add a Todo.js file. We’re going to export an object containing four methods for the four requests:

const LocalStorage = require('node-localstorage').LocalStorage;
const localStorage = new LocalStorage('./db');

module.exports = {

    get(request, response) {

    },

    create(request, response) {

    },

    update(request, response) {

    },

    delete(request, response) {

    }
};

Each method will get access to a request and response object. We also need to import the LocalStorage package since we’re going to use that in place of a real database. It will automatically create a db folder for you in the root directory.

Let’s go in order and see how we can get back todos using the get method.

Get route

We want to either get all or a specific todo, based on whether the id has been provided in the URL or not. We also want to check whether we have a localStorage item set, so we don’t end up with an error. This leaves us with the following checks:

get(request, response) {
    if (localStorage.getItem('todos')) {
        if (!request.params.id) {
            // Return all todos
        } else {
            // Return single todo
        }
    } else {
        // No todos set on localStorage, fall back to empty response
    }
}

To get URL parameters, we simply need to access the request.params object. The name of the property will be the one specified in app.route. (_:id_) To return a JSON response, we can call response.json with an object we want to return as a response:

get(request, response) {
    if (localStorage.getItem('todos')) {
        if (!request.params.id) {
            response.json({
                todos: JSON.parse(localStorage.getItem('todos'))
            });
        } else {
            const todo = JSON.parse(localStorage.getItem('todos')).filter(todo => todo.id === parseInt(request.params.id, 10));

            response.json({
                todo
            });
        }
    } else {
        response.json({
            todos: []
        });
    }
}

If we don’t even have todos in localStorage, we can return an empty array. Otherwise, we can return the items stored in localStorage. Since we can only store strings, we need to call JSON.parse on the object. The same applies when we want to access a single todo. But this time, we also want to filter for a single item.

If you refresh the page, you’ll get back and empty todo list.

Post route

Let’s populate the array with some items. This time, we want to send the request data using a x-www-form-urlencoded content type. Since we can’t send a POST request right inside the browser, we need to find another way. For this task, I’m using the popular Postman app. You can download and install it for free.

Open the app and create a new request. Set the method type to POST and the body to x-www-form-urlencoded. We only want to add a new todo if a name and a completed flag have been provided.

To get the values from the request inside Express, we can access request.body. If you, however, send a post request and try to log out request.body, you’ll notice that it is undefined. This is because express by default can’t handle URL encoded values. To make them accessible through JavaScript, we have to use a middleware. Add the following line to your server.js file, before you define the routes:

app.use(express.urlencoded({ extended: true }));

Now if you send the POST request and you try to log out request.body again, you’ll get the values logged out to your console.

So we can start by checking whether we have the two values in the request and if not, we can send an error specifying the problem:

create(request, response) {
    if (request.body.name && request.body.completed) {
        // Add new todo
    } else {
        response.json({
            error: '⚠️ You must provide a name and a completed state.'
        });
    }
}

The way we want to add a new item is we simply want to get the todos from localStorage if there’s any, parse the JSON and push a new object to the array. Then convert it back to JSON and of course, send a response to let us know if we were successful.

if (request.body.name && request.body.completed) {
    const todos = JSON.parse(localStorage.getItem('todos')) || [];

    todos.push({
        id: todos.length,
        name: request.body.name,
        completed: request.body.completed === 'true'
    });

    localStorage.setItem('todos', JSON.stringify(todos));

    response.json({
        message: 'Todo has been successfully created. 🎉'
    });
}

Note that since we might not have todos present in the localStorage, we need to fall back to an empty array. Also note that since we’re getting the requests as strings, we need to cast the completed flag to a boolean.

Put route

Once we have enough items in our todo list, we can try to update them. Again, we need to check for the presence of an id and either a name or a completed flag.

update(request, response) {
    if (request.params.id && (request.body.name || request.body.completed)) {
        // Update todo
    } else {
        response.json({
            error: '⚠️ You must provide an id and a property to update.'
        });
    }
}

We want to follow a similar logic we did for the create method: Parse the localStorage data, update the item in the array where the id matches the one passed as a request param, convert the data back to JSON and send a success response:

if (request.params.id && (request.body.name || request.body.completed)) {
    const todos = JSON.parse(localStorage.getItem('todos'));

    todos.forEach(todo => {
        if (parseInt(request.params.id, 10) === todo.id) {
            todo.name = request.body.name || todo.name;

            if (request.body.completed) {
                todo.completed = request.body.completed === 'true';
            }
        }
    });

    localStorage.setItem('todos', JSON.stringify(todos));

    response.json({
        message: 'Todo has been successfully updated. 🎉'
    });
}

Remember that we want to cast the completed flag into a boolean. And the reason why we can’t do logical OR just like we did for todo.name is because in case we want completed to be set to false, it would always fall back to the default todo.completed value.

Delete route

Probably the shortest and simplest method of all will be the delete. All we have to do is filter out the item where the id matches the one passed into the endpoint:

delete(request, response) {
    if (request.params.id) {
        const todos = JSON.parse(localStorage.getItem('todos')).filter(todo => todo.id !== parseInt(request.params.id, 10));

        localStorage.setItem('todos', JSON.stringify(todos));

        response.json({
            message: 'Todo has been successfully removed. 🗑️'
        });
    } else {
        response.json({
            error: '⚠️ You must provide an id.'
        });
    }
}

And reassign its stringified version back to todos inside localStorage.

Conclusion

Now you have a working API in place to handle todo items. I’ll leave the UI part up for you. The great way about this approach is that every operation is separated into a different method. This way your API is more easily scalable. It also helps reducing time looking for bugs. If you are experiencing a problem with one of the requests, you can quickly pinpoint where and what went wrong. You’ll know that the problem lies in one single function.

If you were wondering about the look and feel of the JSON response I was getting throughout the tutorial, I’m using the JSON Viewer. Chrome extension, which you can get at the provided link. If you would like to mess around with the final project, you can reach it at the express-api Github repo.

Thank you for reading through. Whether if you have any experience building APIs and working with Express or not, share your thoughts in the comments below and let us know what is your approach.

#javascript #express #nodejs #webdevelopment #programming

What is GEEK

Buddha Community

How to Build a Simple REST API using Express
Wilford  Pagac

Wilford Pagac

1594289280

What is REST API? An Overview | Liquid Web

What is REST?

The REST acronym is defined as a “REpresentational State Transfer” and is designed to take advantage of existing HTTP protocols when used for Web APIs. It is very flexible in that it is not tied to resources or methods and has the ability to handle different calls and data formats. Because REST API is not constrained to an XML format like SOAP, it can return multiple other formats depending on what is needed. If a service adheres to this style, it is considered a “RESTful” application. REST allows components to access and manage functions within another application.

REST was initially defined in a dissertation by Roy Fielding’s twenty years ago. He proposed these standards as an alternative to SOAP (The Simple Object Access Protocol is a simple standard for accessing objects and exchanging structured messages within a distributed computing environment). REST (or RESTful) defines the general rules used to regulate the interactions between web apps utilizing the HTTP protocol for CRUD (create, retrieve, update, delete) operations.

What is an API?

An API (or Application Programming Interface) provides a method of interaction between two systems.

What is a RESTful API?

A RESTful API (or application program interface) uses HTTP requests to GET, PUT, POST, and DELETE data following the REST standards. This allows two pieces of software to communicate with each other. In essence, REST API is a set of remote calls using standard methods to return data in a specific format.

The systems that interact in this manner can be very different. Each app may use a unique programming language, operating system, database, etc. So, how do we create a system that can easily communicate and understand other apps?? This is where the Rest API is used as an interaction system.

When using a RESTful API, we should determine in advance what resources we want to expose to the outside world. Typically, the RESTful API service is implemented, keeping the following ideas in mind:

  • Format: There should be no restrictions on the data exchange format
  • Implementation: REST is based entirely on HTTP
  • Service Definition: Because REST is very flexible, API can be modified to ensure the application understands the request/response format.
  • The RESTful API focuses on resources and how efficiently you perform operations with it using HTTP.

The features of the REST API design style state:

  • Each entity must have a unique identifier.
  • Standard methods should be used to read and modify data.
  • It should provide support for different types of resources.
  • The interactions should be stateless.

For REST to fit this model, we must adhere to the following rules:

  • Client-Server Architecture: The interface is separate from the server-side data repository. This affords flexibility and the development of components independently of each other.
  • Detachment: The client connections are not stored on the server between requests.
  • Cacheability: It must be explicitly stated whether the client can store responses.
  • Multi-level: The API should work whether it interacts directly with a server or through an additional layer, like a load balancer.

#tutorials #api #application #application programming interface #crud #http #json #programming #protocols #representational state transfer #rest #rest api #rest api graphql #rest api json #rest api xml #restful #soap #xml #yaml

An API-First Approach For Designing Restful APIs | Hacker Noon

I’ve been working with Restful APIs for some time now and one thing that I love to do is to talk about APIs.

So, today I will show you how to build an API using the API-First approach and Design First with OpenAPI Specification.

First thing first, if you don’t know what’s an API-First approach means, it would be nice you stop reading this and check the blog post that I wrote to the Farfetchs blog where I explain everything that you need to know to start an API using API-First.

Preparing the ground

Before you get your hands dirty, let’s prepare the ground and understand the use case that will be developed.

Tools

If you desire to reproduce the examples that will be shown here, you will need some of those items below.

  • NodeJS
  • OpenAPI Specification
  • Text Editor (I’ll use VSCode)
  • Command Line

Use Case

To keep easy to understand, let’s use the Todo List App, it is a very common concept beyond the software development community.

#api #rest-api #openai #api-first-development #api-design #apis #restful-apis #restful-api

Lets Cms

Lets Cms

1652251528

Opencart REST API extensions - V3.x | Rest API Integration, Affiliate

Opencart REST API extensions - V3.x | Rest API Integration : OpenCart APIs is fully integrated with the OpenCart REST API. This is interact with your OpenCart site by sending and receiving data as JSON (JavaScript Object Notation) objects. Using the OpenCart REST API you can register the customers and purchasing the products and it provides data access to the content of OpenCart users like which is publicly accessible via the REST API. This APIs also provide the E-commerce Mobile Apps.

Opencart REST API 
OCRESTAPI Module allows the customer purchasing product from the website it just like E-commerce APIs its also available mobile version APIs.

Opencart Rest APIs List 
Customer Registration GET APIs.
Customer Registration POST APIs.
Customer Login GET APIs.
Customer Login POST APIs.
Checkout Confirm GET APIs.
Checkout Confirm POST APIs.


If you want to know Opencart REST API Any information, you can contact us at -
Skype: jks0586,
Email: letscmsdev@gmail.com,
Website: www.letscms.com, www.mlmtrees.com
Call/WhatsApp/WeChat: +91–9717478599.

Download : https://www.opencart.com/index.php?route=marketplace/extension/info&extension_id=43174&filter_search=ocrest%20api
View Documentation : https://www.letscms.com/documents/api/opencart-rest-api.html
More Information : https://www.letscms.com/blog/Rest-API-Opencart
VEDIO : https://vimeo.com/682154292  

#opencart_api_for_android #Opencart_rest_admin_api #opencart_rest_api #Rest_API_Integration #oc_rest_api #rest_api_ecommerce #rest_api_mobile #rest_api_opencart #rest_api_github #rest_api_documentation #opencart_rest_admin_api #rest_api_for_opencart_mobile_app #opencart_shopping_cart_rest_api #opencart_json_api

Lets Cms

Lets Cms

1652251629

Unilevel MLM Wordpress Rest API FrontEnd | UMW Rest API Woocommerce

Unilevel MLM Wordpress Rest API FrontEnd | UMW Rest API Woocommerce Price USA, Philippines : Our API’s handle the Unilevel MLM woo-commerce end user all functionalities like customer login/register. You can request any type of information which is listed below, our API will provide you managed results for your all frontend needs, which will be useful for your applications like Mobile App etc.
Business to Customer REST API for Unilevel MLM Woo-Commerce will empower your Woo-commerce site with the most powerful Unilevel MLM Woo-Commerce REST API, you will be able to get and send data to your marketplace from other mobile apps or websites using HTTP Rest API request.
Our plugin is used JWT authentication for the authorization process.

REST API Unilevel MLM Woo-commerce plugin contains following APIs.
User Login Rest API
User Register Rest API
User Join Rest API
Get User info Rest API
Get Affiliate URL Rest API 
Get Downlines list Rest API
Get Bank Details Rest API
Save Bank Details Rest API
Get Genealogy JSON Rest API
Get Total Earning Rest API
Get Current Balance Rest API
Get Payout Details Rest API
Get Payout List Rest API
Get Commissions List Rest API
Withdrawal Request Rest API
Get Withdrawal List Rest API

If you want to know more information and any queries regarding Unilevel MLM Rest API Woocommerce WordPress Plugin, you can contact our experts through 
Skype: jks0586, 
Mail: letscmsdev@gmail.com,
Website: www.letscms.com, www.mlmtrees.com,
Call/WhatsApp/WeChat: +91-9717478599.  

more information : https://www.mlmtrees.com/product/unilevel-mlm-woocommerce-rest-api-addon

Visit Documentation : https://letscms.com/documents/umw_apis/umw-apis-addon-documentation.html

#Unilevel_MLM_WooCommerce_Rest_API's_Addon #umw_mlm_rest_api #rest_api_woocommerce_unilevel #rest_api_in_woocommerce #rest_api_woocommerce #rest_api_woocommerce_documentation #rest_api_woocommerce_php #api_rest_de_woocommerce #woocommerce_rest_api_in_android #woocommerce_rest_api_in_wordpress #Rest_API_Woocommerce_unilevel_mlm #wp_rest_api_woocommerce

Chaz  Homenick

Chaz Homenick

1602725748

Why You Should Consider Low-Code Approach to Building a REST API

APIs have been around for decades – they allow different systems to talk to each other in a seamless, fast fashion – yet it’s been during the past decade that this technology has become a significant force.

So then why all the interest in APIs? We all know the usual stories – Uber, Airbnb, Apple Pay… the list goes on, and the reasons are plentiful. Today the question is, how? Perhaps you are looking to differentiate your business or want a first-mover advantage.  How can you execute quickly and at low cost/risk to try new market offerings?

An API provides several benefits to an organisation, but without a dedicated team of trained developers, it might seem like an implausible option. Developers are expensive, and it can take months to develop an API from the ground up. If you don’t fancy outsourcing or have the capability in house to build internal APIs, a low-code platform might just be the answer.

Before You Begin: Plan long-term, start small.

For a small one-page application, this might only be a day or two of talking with stakeholders and designing business logic. The purpose of this first step is to ensure that the API will cover all use cases and provides stakeholders with what they need. Refactoring an entire coding design due to missing business logic is not only frustrating for the development team but adds high cost and time to the API project.

During the planning and design stage, remember that running an API requires more infrastructure than just resources to execute endpoint logic. You need a database to store the data, an email system to send messages, storage for files, and security to handle authorisation and authentication. These services can be farmed out to cloud providers to expedite the API build process (e.g. AWS provides all these infrastructure components, but Microsoft Azure is an optional cloud provider with SendGrid as the email application.)

**Planning considerations: **An API “speaks” in JSON or XML, so the output provided to client applications should be decided. Should you choose to later create endpoints for public developer consumption, you could offer both for ease-of-use and fostering more adoption. Ensuring the API follows OpenAPI standards will encourage more adoption and attract more developers.

#api #rest-api #api-development #restful-api #low-code-platform #low-code #build-a-rest-api #low-code-approach