How to Build a RESTful API with Authentication in 5 minutes — all from your command line (Part 1)

If the title of this article excites you, then get ready to achieve developer nirvana in the next 5 minutes. Thanks to the power of modern tools and frameworks, it‘s now possible to build a fully-functional REST API complete with authentication in less time than it takes to brew a pot of coffee.

In this step-by-step guide, we‘ll create a RESTful API to manage an online store‘s product catalog. The API will allow creating, reading, updating and deleting products from a MongoDB database. We‘ll also enable authentication to secure the API endpoints. And the best part – it can all be done right from the command line without writing barely any code!

Here‘s an overview of what we‘ll cover:

  1. A lightning-fast intro to REST APIs and why they‘re awesome
  2. Using the LoopBack framework to turbocharge API development
  3. Creating a new LoopBack application via command line
  4. Setting up a MongoDB database and generating data models
  5. Enabling authentication to protect API routes
  6. Testing the API using the built-in Swagger explorer

Alright, let‘s jump in and get our API up and running in record time!

Why REST APIs Rock

Before we dive into building, let‘s do a quick recap of what a REST API is and why they‘ve become the backbone of modern web and mobile applications.

An API (Application Programming Interface) defines a set of rules for how different software applications can communicate with each other. APIs make it possible to modularize application architectures into self-contained services that can be developed and scaled independently. This microservices approach has become increasingly popular versus traditional monolithic architectures.

REST (Representational State Transfer) is a popular architectural style for building web APIs where the primary means of communication is exchanging JSON or XML data over HTTP. The core principles of REST include:

  • Resources: All data is modeled as a set of resources identified by URLs
  • HTTP methods: Resources are manipulated using standard HTTP methods like GET, POST, PUT, DELETE
  • Stateless: Each request is independent and contains all the info needed to be processed by the server
  • Uniform interface: Resources have a consistent, well-defined interface for interaction

Some benefits of REST APIs:

  • Scalability: REST is lightweight and highly scalable
  • Flexibility: Works with any programming language or framework
  • Mashups: Enables mixing and matching data from multiple APIs
  • Speed: Requests can be cached for faster performance

With the rise of cloud computing and mobile apps, being able to build RESTful backends has become an essential skill. But building an API from scratch requires significant boilerplate code. That‘s where awesome frameworks like LoopBack come to the rescue!

What is LoopBack?

LoopBack is a highly-extensible, open-source Node.js framework that enables you to quickly create dynamic end-to-end REST APIs. It‘s a part of the API creation suite by IBM and is so powerful that you can build a fully-featured API without writing much code.

Some key benefits of LoopBack:

  • Saves development time by generating a ton of boilerplate code
  • Integrates easily with many popular databases and services
  • Built-in Swagger API explorer for testing and documentation
  • Rich access control and authentication features

One of the coolest parts of LoopBack is its command line interface (CLI) that allows you to scaffold an entire application right from your terminal. You can create data models, set up access controls, enable authentication, run db migrations, and more without leaving the command line.

Under the hood, LoopBack uses Express, one of the most popular web frameworks for Node. So you get all the performance benefits of Express but with way less coding required.

Alright, now that we know why REST APIs and LoopBack are so awesome, let‘s get our hands dirty and build one! It‘s time to unleash the power of the CLI.

Creating a LoopBack Application

Prerequisites

Make sure you have the following installed on your system:

  • Node.js (version 8.9+)
  • npm (version 5.5.1+)
  • MongoDB (we‘ll use this for our database)

I‘ll assume you already have a MongoDB server up and running on the default port 27017. If not, go ahead and install that now.

Install LoopBack CLI

Open up your terminal and install the LoopBack CLI globally via npm:

npm install -g loopback-cli

This will give you access to the lb command for generating all kinds of LoopBack awesomeness.

Generate the Application

Now let‘s scaffold a new LoopBack application with the following command:

lb

You‘ll be asked a series of questions to configure the application. Here‘s how I answered for our online store API:

? What‘s the name of your application? online-store
? Enter name of the directory to contain the project: online-store
? Which version of LoopBack would you like to use? 3.x (current)
? What kind of application do you have in mind? api-server (A LoopBack API server with local User auth)

Bam! With those simple answers, LoopBack generated the entire scaffolding for our API server. No coding required!

Let‘s test it out. cd into the application directory and start the server:

cd online-store
node .

You should see output like this:

Web server listening at: http://localhost:3000
Browse your REST API at http://localhost:3000/explorer

Pop open your browser and go to http://localhost:3000/explorer. You‘ll be greeted by the glorious sight of the LoopBack API Explorer:

[insert screenshot of API Explorer]

This is a full Swagger UI that allows you to visualize and test all the API endpoints right from the browser. It‘s generated automatically based on your LoopBack models and routes. How cool is that?!

Alright, let‘s secure our API by adding authentication.

Enable Authentication

Adding authentication to a LoopBack app is a breeze. We want to restrict access to most of our API endpoints to authenticated users. Luckily, LoopBack has a built-in User model with authentication methods like login, logout, and password reset.

From your project root, run the following command:

lb acl

You‘ll be prompted with:

? Select the model to apply the ACL entry to: (all existing models)
? Select the ACL scope: All methods and properties
? Select the access type: All (match all types)
? Select the role All users
? Select the permission to apply Explicitly deny access

This set of answers tells LoopBack to restrict access to all models, methods, and endpoints to only authenticated users by default.

Restart your server (node .) and go back to the API Explorer. You‘ll see that most routes are now tagged with a closed lock icon. That means you need to be authenticated to access them.

To login, expand the POST /users/login route and click the "Try it out!" button. Enter the credentials of a user that you created and click "Execute". If the login is successful, you‘ll see the response include an id property – that‘s the access token.

Copy that access token and paste it into the "api_key" field at the top of the Explorer. Now you‘re authenticated and can make requests to the protected routes!

Connect a Database

Install MongoDB Connector

By default, LoopBack uses an in-memory data store. That‘s fine for testing but let‘s hook up a real database. We‘ll use MongoDB in this example.

First, install the LoopBack MongoDB connector:

npm install --save loopback-connector-mongodb

Create a DataSource

Now we‘ll create a DataSource to interface with our Mongo database. Run the following command:

lb datasource

Answer the prompts like this:

? Enter the data-source name: mongo_ds
? Select the connector for mongo_ds: MongoDB (supported by StrongLoop)
? Connection String url to override other settings (eg: mongodb://username:password@hostname:port/database):
? host: localhost
? port: 27017
? user:
? password:
? database: online_store
? Install loopback-connector-mongodb@^1.4 Yes

This configures our app to connect to a local MongoDB database called "online_store".

Create Models

Now comes the fun part – creating models to represent our application data. For our online store example, we‘ll create a simple Product model.

Run the model generator:

lb model

And fill in the details at the prompts:

? Enter the model name: product
? Select the data-source to attach product to: mongo_ds (mongodb)
? Select model‘s base class PersistedModel
? Expose product via the REST API? Yes
? Custom plural form (used to build REST URL):
? Common model or server only? common
Let‘s add some product properties now.

Enter an empty property name when done.
? Property name: name
   invoke   loopback:property
? Property type: string
? Required? Yes

Let‘s add another product property.
Enter an empty property name when done.
? Property name: price
   invoke   loopback:property
? Property type: number
? Required? Yes

With those steps, we now have a Product model hooked up to our Mongo database with a REST API interface. LoopBack will automatically create the corresponding routes and controller logic. Again, no manual coding required!

Restart your app (node .) and you‘ll see the new Products routes show up in the API Explorer, ready to be tested.

Putting It All Together

Let‘s see our API in action! Make sure you‘re authenticated in the Explorer by logging in and setting the access token.

Expand the POST /products route and create a new product:

{
  "name": "Awesome T-Shirt",
  "price": 19.99
}

Click "Execute" and you‘ll get back the created product object, now with a unique id assigned by Mongo.

Next, expand the GET /products route and click "Execute" (no need to provide any parameters). You‘ll see an array with the product we just added.

Finally, try accessing the GET /products route in your browser without the access token. You should get back an "Authorization Required" error, since this route is protected.

Next Steps

Congrats, you just built a REST API with authentication…in 5 minutes…all from the command line! You now have a solid foundation to build all kinds of cool web and mobile applications.

Where you go from here is up to you and your imagination. A few ideas:

  • Add more models and relations to flesh out your application
  • Customize the API Explorer to match your brand
  • Set up email-based authentication
  • Write some unit tests for your API routes
  • Connect a frontend framework like React, Angular, or Vue
  • Deploy to a cloud hosting service like Heroku or AWS

I hope this lightning-fast introduction to LoopBack has opened your eyes to the amazing power of CLI tools and scaffolding frameworks. While understanding the underlying concepts is important, you don‘t always have to build everything from absolute scratch. Let tools like LoopBack handle the heavy lifting so you can focus on turning your ideas into reality.

Happy API building!

Similar Posts