Quantcast
Channel: Runscope Blog - API Monitoring and Testing
Viewing all articles
Browse latest Browse all 231

Playing with Node.js and the Runscope API on Glitch

$
0
0
 logo-day 

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.

The Glitch code editor showing the runscope-oauth project with the beginning of the server.js JavaScript file

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.

The Glitch website, showing the runscope-oauth project's detail page, with three buttons (Preview, View Source, and Remix your own) under the project's name, and the beginning of its README

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) {
    // TODO: retrieve user profile from Runscope API
  }
));

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);
      }
    });
  }
));
Glitch editor running the runscope-oauth application, and showing where the user can find the Logs button to open the Activity Log menu for the app, and the console.log statement that prints the Runscope user information after a successful authentication

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:

Displaying the list of buckets in a Runscope account, after successful authentication of the runscope-batch-edit Glitch app

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 Glitch runscope-batch-edit app, showing the Set Schedule screen for a bucket. There's a radio button form the user can select the available schedule options for their tests: 1/5/15/30min, 1/6h, and 1 day. There's another checkbox form below that showing the list of tests in the bucket, and a submit form to make the API call that will update the tests. The Glitch runscope-batch-edit app, showing the Set Environment screen for a bucket. There's a radio button form at the top where the user can select any shared environments for that bucket. Below there's another checkbox form, where the user can select which tests to modify, and a submit form button to make the API call that will update the tests

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 timeseries chart using C3.js:

The Glitch app runscope-api-metric, displaying the uptime information for the app, as well as metrics from the Runscope API Metrics endpoint: total number of test runs, region, timeframe, and response time 95th percentile. It also shows a line timeseries chart, with two lines representing the success ratio and average response time in ms for an API monitor

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:

The Glitch runscope-api-metric app, showing the screen after a successful authentication with a user's Runscope credentials. It contains a simple form with two text fields: one for the bucket key with the placeholder text your_bucket_key, and one for the test id with the placeholder text your_test_id. There's a submit form button below the two fields, that will make the API call to the Runscope API Metrics endpoint with the information in the text fields.

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

The Runscope website, highlighting the URL for a Runscope API test. It shows the URL: https://www.runscope.com/radar/o8mclwfrxtz0/7650e8d1-19af-4669-bb0e-3fcfef9a7335/overview, and there's two pink boxes highlighting the Bucket Key (o8mclwfrxtz0), and the Test ID (7650e8d1-19af-4669-bb0e-3fcfef9a7335)

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:

The Glitch UI showing the details of the runscope-batch-edit project, and the buttons Preview, View Source, and Remix your own at the bottom

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

  • On Glitch, make sure you're on 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!


If you're new to API monitoring and testing, learn more about Runscope's cloud-based API monitoring solution and sign up for your free trial account today.



Viewing all articles
Browse latest Browse all 231

Trending Articles