-
Notifications
You must be signed in to change notification settings - Fork 46
Using BadgeKit API
You can use the BadgeKit API to implement badging processes in your own sites and applications. Whether you're using the BadgeKit Web app or your own admin interface, you can use the BadgeKit API endpoints to interact with badge data - and receive notification of events - by configuring your webhook. This guide will begin to show you how you can utilize the BadgeKit API in your own sites.
The pages in this wiki provide tutorial-style material on using the API. For a basic reference outlining the API endpoints and data, see the docs.
The API guides use node.js examples to demonstrate the key processes you need to connect BadgeKit to your own earner-facing site. If you're using other languages/ platforms, you should be able to see how you can use BadgeKit to deliver your implementation.
- Before you start
- References
- Preparation
- Admin levels
- Example - Retrieve Badge Data
- Authentication data
- Request data
- Making a request
- Processing the results
- Badge Data
- Webhooks
- Review
- Award
- BadgeKit Guide List
Before you start using this guide, you should first have a working installation of the BadgeKit API, which should be running before you attempt to run your own code. If you are using the BadgeKit Web app, you may wish to have it running too. See the following guides for getting your installation(s) setup:
- BadgeKit Self-Hosting Guide Includes detailed instructions for setting up both BadgeKit API and Web app.
- BadgeKit API
You will need the master secret you set during your BadgeKit API installation to access the endpoints and to receive notifications via your webhook URL.
If you look at the BadgeKit Web app dependencies, you will see badgekit-api-client is in there. The app uses this client to access the API, so it's worth checking out if you're using node.js to work with BadgeKit in your own site.
Let's work through a simple example that will demonstrate how you access the API endpoints. Although the initial code examples are in node.js, you should be able to see how the key processes work regardless of the technology you're using.
For an overview of the available endpoints in BadgeKit API, see the project docs.
To access any of the data handled by the API, your code needs to authenticate its requests using a JWT token in the authorization header, which we will demonstrate below. For a fuller explanation see the Authorization guide.
Since we need to sign our requests to the API, we will use JWS for signing within our node app. You can install this in your node app directory as follows:
npm install jws
We will also be using express
- if you are starting a new node app to use with the BadgeKit API you may wish to follow the steps in this guide: Getting Started with Node.js on Heroku - you can use this as a guide even if you aren't using Heroku, just omit the steps related specifically to Heroku for a local setup, which you can later push to an online service of your choice.
The code in this guide can be used in a standard node.js setup - if you have a "Hello World" app after following the tutorial linked above, you can add your code to that:
var express = require("express");
var logfmt = require("logfmt");
var app = express();
app.use(logfmt.requestLogger());
var port = Number(process.env.PORT || 5000);
app.listen(port, function() {
console.log("Listening on " + port);
});
Using this setup, running foreman start
will start your app running at port 5000, so you could access it in the browser as follows for a local install: localhost:5000
.
Before we get stuck into the details of making an API call, let's take a moment to explain the admin levels that are built into BadgeKit. You may have noticed that the BadgeKit API database has tables for systems
, issuers
and programs
. These are entirely optional levels of admin we built into the data following experiences with real-world badging systems. You do not need to use these in your own sites - as long as you have a system
entry in your BadgeKit API database, your badges can simply be associated with that system. If you do choose to use the other admin levels, here is how they work:
- a
system
may include multipleissuers
- an
issuer
may include multipleprograms
- a badge can belong to a
system
,issuer
orprogram
These levels are designed to accommodate the fact that a badging system could be an umbrella organization such as a city-wide educational authority, with multiple smaller organizations issuing badges (e.g. schools, libraries etc) and multiple educational programs awarding badges, for example on particular subjects or disciplines.
However you choose to organize your admin levels, each time you make a call to the API you will need to specify them. The simplest API calls require at least the name of a system, and you can optionally include issuer and program names to filter the data returned.
The API endpoints provide the ability to administer all information related to your published badges. A range of GET
, POST
and PUT
requests give you control over your badge and assessment data. Additionally, the API sends notifications to your webhook so that you can respond to badge issuing events. The API is not designed to store earner information - so that you retain control over the data for your community.
To make the request and sign it in node, we will use http
and jws
:
var http = require("http");
var jws = require('jws');
When we make a request, we will sign a set of data items representing authentication claims. You can see an overview of the claims on the Authorization page and should configure them to suit your own system. The excerpt below demonstrates a structure you could use:
var claimData = {
header: {typ: 'JWT', alg: 'HS256'},
payload: {
key: 'master',
exp: Date.now() + (1000 * 60),
method: 'GET',
path: '/systems/badgekit/badges'
},
secret: 'yoursecret'
};
We use the HS256
algorithm, with master
as the key and the current time plus 60 seconds as the expiry time for this token. You will need to alter GET
to POST
or PUT
for posting or updating data rather than fetching it. Include the path for the endpoint you need - this example is to retrieve all badges in the badgekit
system (alter it if your system has a different name - it should be whatever you entered in the system
database table as slug
). Finally, you should set the secret to the master secret value you chose when you configured your BadgeKit API.
We will sign the data and include the resulting token when we make the request.
If you want to retrieve badges for a particular issuer or program, append your path as follows:
/* example above */
"/systems/:systemSlug/badges"
/* example using particular issuer */
"/systems/:systemSlug/issuers/:issuerSlug/badges"
/* example using particular program */
"/systems/:systemSlug/issuers/:issuerSlug/programs/:programSlug/badges"
Most of the API calls use this hierarchical structure.
Before trying to retrieve a list of badges, you will of course need to add some badges to your data if you don't have any yet - you can use the BadgeKit Web app to create and publish badges if you have it installed! Otherwise, you will need to add some entries to your
badges
table - NOT thebadgeInstances
table, which is for awarded badges.
Now we can define the request data:
var requestOptions = {
host : 'your.badgekit.api.location.com',
path : '/systems/badgekit/badges',
method : 'GET',
headers: { 'Authorization': 'JWT token="' + jws.sign(claimData) + '"' }
};
Alter the host
value to reflect the location of your BadgeKit API (not including "http" or "https"). The path and method must match the values you included in your claim data or authentication will fail. In the last line we sign the claim data and include the token in the Authorization
header for the request.
With your claim data and request options prepared, you can make a call to your BadgeKit API. The following excerpt demonstrates:
var apiRequest = http.request(requestOptions, function(apiResult) {
apiResult.on('data', function(badgeData) {
//process badgeData
});
});
You can now do what you want with the returned JSON data. The following example shows how you could write data to the page:
app.get('/', function(req, res) {
res.send("Badges: "+badgeData);
});
You can use JSON.parse(badgeData)
to parse the data and access the elements within it in your own algorithm.
You will also need to handle errors and tidy up following your request call:
apiRequest.end();
apiRequest.on('error', function(e) {
console.error(e);
});
When you retrieve the badge data, you will see the JSON structures your sites will be parsing. Badges are included in a badges
array, and each badge has a series of data items associated with it. If you try altering your path to retrieve a specific badge you will see these details a little more clearly:
/* path */
"/systems/:systemSlug/badges/:badgeSlug"
The following demonstrates the returned JSON structure for a single badge:
{
"badge":
{
"id": 31,
"slug": "coffeelandia-assistant-store-manager",
"name": "Coffeelandia Assistant Store Manager",
"strapline": "Achieved level of Assistant Store Manager, can perform various store tasks. Leadership, financial expertise, and dynamic problem solving.",
"earnerDescription": "Earning the Coffeelandia Assistant Store Manager represents significant commitment to the Coffelandia ethos. We believe in fair trade, fair work and fair play: our Assistant Managers represent those values and more. When you earn this badge, you earn a permanent and special place in our Coffelandia family.",
"consumerDescription": "At Coffelandia, we believe in fair trade, fair work and fair play: our Assistant Managers represent those high values and more. Earning the Coffeelandia Assistant Store Manager represents an awesome commitment to the Coffelandia ethos and completion of our rigorous assistant manager training. These badge earners have not only performed all of the roles and duties of all team members, they have also exhibited superior communication skills, dynamic customer service, and perhaps most importantly, they have repeatedly demonstrated a deep and abiding love for coffee and the people who drink it. We only wish that you could smell this badge because it would smell like Coffelandia love.",
"issuerUrl": "www.coffeeland.ia",
"rubricUrl": "",
"timeValue": 0,
"timeUnits": "minutes",
"limit": 0,
"unique": 0,
"created": "2014-04-25T10:10:53.000Z",
"imageUrl": "http://yourbadgekitappsite.com/images/badge/51",
"archived": false,
"system":
{
"id": 1,
"slug": "badgekit",
"url": "http://yourbadgekitappsite.com",
"name": "Lovely System",
"email": null,
"imageUrl": null
},
"criteriaUrl": "http://yourbadgekitappsite.com/badge/coffeelandia-assistant-store-manager/criteria",
"criteria":
[
{
"description": "Performs all roles and duties of a Team Member. ",
"required": 1,
"note": ""
},
{
"description": "Models, upholds, and communicates existing and new policies, practices, and standards. ",
"required": 1,
"note": ""
},
{
"description": "Assists in development of and execution of local sales building and national marketing programs. ",
"required": 1,
"note": ""
}
]
}
}
Note that the badge data in BadgeKit contains a few additional items when compared to the standard badge class structure outlined in the assertion specification.
You could now parse the data within the badge, for example writing the badge image into an HTML element:
res.send("badge: <img src='"+JSON.parse(badgeData).badge.imageUrl+"'/>");
This is a simplistic example, but you can hopefully begin to see how you can use the API to interact with badge data.
In addition to a range of GET
, POST
and PUT
requests to interact with the data, the API also sends notifications to a webhook URL of your choice. You can configure a webhook by adding a record to the webhooks
table in the database, including the URL and a secret you will use to decode the data.
BadgeKit sends notification to your webhook URL when an application review is submitted, when a badge is issued and when a badge is revoked. If you are using the assessment process (i.e. letting earners submit applications plus evidence to apply for badges, then reviewing those applications), both the review
and award
actions will be relevant to you. If you are issuing badges without assessment (e.g. via claim code or directly to email), only the award
action will be relevant.
If you want to understand more about the assessment process, see Assessment with BadgeKit.
The revoke
webhook fires when an issued badge is revoked - see the webhooks page in the docs for more.
The API sends data along with the review
action when a reviewer assesses a pending application (for example in the BadgeKit Web app) - typically you would then contact the earner indicating whether or not the application was approved.
Note that an approved review is not enough to issue a badge to an earner - you must call on the API endpoints explicitly to create a badge instance. This is to help in cases where the earner may be a child or young person, in which case you can first offer the badge, then create the instance if the earner decides to accept it, potentially in conjunction with intervention from an adult.
The API sends data along with the award
action when a badge is issued. This occurs when a badge instance is created via the API. The award
action fires at the webhook when any badge is issued, regardless of whether or not assessment was involved.
The award
webhook allows you to carry out any follow-up tasks you wish to implement with the earner, for example offering to let them push a new badge to a backpack. BadgeKit will NOT contact the earner when you issue them a badge, instead the API sends notification to your webhook so that you can handle the earner interaction yourself.
See the webhooks page in the repo docs for more detail.
If you're integrating BadgeKit (Web app and API) with your own earner-facing site, you can use the guides below to complete your implementation. If you follow the guides in the order listed, you learn how to list badges using the API, accept earner applications (which you can then process in the Web app), award and issue badges using the webhook messages.
- Retrieving Badges
- Submitting Applications - with evidence
- Application Review Webhooks - responding to application reviews being submitted
- Awarding Badges - issuing by creating badge instances, optionally on earner acceptance
- Badge Issued Webhooks - responding to badges being awarded
The in-app docs cover all of the API endpoints, with the above guides providing a more detailed overview of carrying out typical badging processes.
For support working with BadgeKit or Open Badges, use any of the following channels:
- Post general questions in our Community Google Group and post technical questions in our Dev Google Group.
- Reach members of the Open Badges team directly on IRC (irc.mozilla.org) on the #badges channel.
- Email questions directly to [email protected] and a member of the team will follow-up.
- Follow or tweet the Open Badges team @OpenBadges.
- Get involved or submit issues via the GitHub repos - feedback is always appreciated!