Playing With Node.js and the Runscope API on Glitch

综合技术 2018-03-07

Playing With Node.js and the Runscope API on Glitch

DZone's Guide to

Playing With Node.js and the Runscope API on Glitch

A developer shares his experiences with the Glitch development environment, and how it used it to create a Node.js app that made use of an API.

Heitor Tashiro Sergent

Mar. 07, 18 ·
Integration Zone

Free Resource

Join the DZone community and get the full member experience.

Are your API program basics covered? Read the 5 Pillars of Full Lifecycle API Management eBook

I've been wanting to create a project on Glitch for quite some time. Glitch is a startup/product/friendly community where you can create and remix Node.js projects , use an online code editor to personalize them, and you don't have to worry about hosting or deployment. And it's free! It's a really great way to start a project and prototype an idea, without having to worry about those million little things that can get in the way of your dream app.

I thought it'd be fun to share a few projects I made using the Runscope API , and how you can use them to extend Runscope functionality or create custom features for use cases you might have, like creating a custom dashboard that displays API metrics using C3.js .

Here we'll take a look at three projects:

  • runscope-oauth - Uses Passport.js + passport-oauth2 + the Runscope API authentication.
  • runscope-batch-edit - Remix of runscope-oauth, uses the Runscope API to get a list of user buckets + list of tests in a bucket + set multiple tests schedules + set multiple tests default environments.
  • runscope-api-metric - Remix of runscope-oauth, uses the Runscope API to get a test's metrics information (avg. response time, success ratio, etc.) + express-healthcheck Node.js package to display app's uptime information.

Clicking on the project's link will take you to the Glitch homepage, and show you a popup with the README for the project, and also three buttons to: preview the app live, view the source code, or "Remix your own" to make a copy of the project under your account so you can play with it.

Let's take a closer look at them!

Authenticating With the Runscope API OAuth 2.0

Our first project is actually a remix of another project ( github-oauth ). You can give it a try here:

And you can view the source code directly here:

The goal of our first app is to ask the user to authenticate with their Runscope credentials, and show a success screen if it works. We do this by using Passport , implementing the passport-oauth2 strategy, and setting up the code to use the authorization, token, and callback URLs found in our API Authentication docs. In our server.js file :

passport.use(new OAuth2Strategy({
    authorizationURL:   'https://www.runscope.com/signin/oauth/authorize',
    tokenURL:           'https://www.runscope.com/signin/oauth/access_token',
    callbackURL:        'https://' + process.env.PROJECT_DOMAIN + '.glitch.me/auth/runscope/callback',
    clientID:           process.env.RUNSCOPE_CLIENT_ID,
    clientSecret:       process.env.RUNSCOPE_CLIENT_SECRET
  },
  function(accessToken, refreshToken, profile, cb) {

  }
));

Our project also includes an example of using the `request` package to grab the authenticated user's account information and log it to the console, but we don't display it on the success page:

...
  },
  function(accessToken, refreshToken, profile, cb) {
    // retrieve user profile from Runscope API
    request({
      url: 'https://api.runscope.com/account',
      auth: {
        'bearer': accessToken
      }
    }, function(err, res) {
      if(err) {
        console.log('error getting account details: ' + err);
        cb(err, null)
      } else {
        var body = JSON.parse(res.body);
        console.log(body);
        return cb(null, body.data);
      }
    });
  }
));

This is our starting point in creating an application that uses the Runscope API, and other users will be able to use with their Runscope credentials.

Batch Editing Schedules and Default Environment

Our second project is a remix of our first project and builds on its initial functionality. You can give it a spin here:

It asks the user to authenticate with its Runscope account login, and then displays a list of the user's buckets:

We do this by using the request package, and the Buckets List endpoint:

app.get('/getBuckets', requireLogin,
  function(req, res) {
    request({
      url: 'https://api.runscope.com/buckets',
      auth: {
        'bearer': authToken
      }
    }, function(err, response) {
      if(err) {
        console.log('error getting account details: ' + err);
        res.send("An error occurred");
      } else {
        var body = JSON.parse(response.body);
        buckets = body.data;
        res.send([username, buckets]);
      }
    });
  }
);

There are two links next to each bucket that will take you to a new page: Set Schedule, and Set Environment. Clicking on them will take you to a new page where you'll be able to see a list of all the tests in your bucket, and either:

  • Set the schedule for multiple tests to be monitored every 1min/5min/15min/1h/1d.
  • Set the default environment for multiple tests to a shared environment, or the environment used in its last test run.

The ability to batch edit tests schedule and default environments is something that currently can't be done via our UI, but we can make it work via our API with a few lines of code.

Getting API Metrics Information and Using C3.js

Our last project started out as a remix of our first project, and displays metrics information from a Runscope API test such as total test runs, average response time, and success ratio. We can test out the project by going to:

It retrieves the information from our new Metrics API endpoint. We also draw a time-series chart using C3.js :

This project is a little more simple. After you authenticate with your Runscope account, there's a form at the top of the page where you can put a Runscope bucket key and test id:

You can find a test's bucket key and id by looking at the URL when you open a test in Runscope:

After that just hit Submit and the app will do its magic and retrieve the API metrics information from the Runscope API.

Remix Your Own Projects!

One of the cool things about Glitch is that you can check the source code for all of the projects above, and remix them to make your own apps. First, open the details page for the project you want to remix, and click on the "Remix your own" button:

After that, we'll need to setup our OAuth 2.0 authorization flow:

  • On Glitch , make sure you're in the code editor for your new app. Click on the "Show Live" button at the top to open your app in a new tab, and copy the app's URL.
  • Go to your Runscope account Applications page , and create a new application. Give your application a name, and paste your app's URL in the website field. For the callback field, paste your URL again, but add `/auth/runscope/callback` at the end. Click on Create Application.
  • Copy your Client ID and Client Secret values.
  • Go back to your project's code editor on Glitch. Open the `.env` file on the left-hand side, and paste your Client ID and Client Secret in their respective variables (make sure you don't add spaces between the "=" symbol).
  • You should be all set! On the Glitch editor for your project, click on the "Show Live" button and test your Runscope authorization flow.

I've really enjoyed using Glitch for the past few days to build out those few sample projects. Not having to worry about setting up a developer environment, or thinking about deployment and hosting is amazing, and checking out the source code for other projects really helped me build out these prototypes.

I hope you can use some of those projects to remix your own Node.js applications, or maybe a learn a thing or two about using the Runscope API , the Passport and request Node.js packages or the C3.js project!

Establish API creation, publishing and discovery as a master practice with the API Management Playbook .

您可能感兴趣的

Monitor Your Webhook Workflows with New Incoming R... API testing and monitoring has traditionally focused solely on outbound requests that simulate what a client of a particular API or endpoint would ex...
Node.js + Socket IO + Apache + PHP cheap webserver... I am new to using node.js and socket io and I am currently hosting my php website on a server, now that I am going to be adding node js and sock...
Cloud Marketplace Becoming The New Wholesale API D... I’m keeping an eye on the AWS Marketplace , as well as what Azure and Google are up to, looking for growing signs of anything API. I’d have to s...
How to get, use, and close a DB connection using c... Callback functions have been around since the early days of JavaScript, but there have never been any standards for using them. How should callbacks b...
Introduction to Kubernetes: How to Deploy a Node.j... While container technology has existed for years, Docker really took it mainstream. A lot of companies and developers now use containers to sh...