Using the Displayer API

Simon Wex edited this page Mar 24, 2015 · 10 revisions

With the Displayer API, you can query the Mozilla Hosted Backpack for public badges awarded to a particular earner. See the documentation for a technical overview and for a step-by-step tutorial to using the API, read on.

Earners can use their Mozilla Backpack to organize their awarded badges into groups and to control whether or not a group of badges is publicly available. Given the earner's email address for the Backpack, you can query for the groups of badges they have made public, displaying these within your own site, application or widget.

To display earner badges, you will need to parse assertion data. If you are new to assertions, see these pages first:

Contents

Converting Email to ID

To discourage storing earner email addresses explicitly, the Mozilla Backpack instead uses a unique ID for each earner. You can pass the earner email address to the convert service to retrieve their Backpack user ID - which you can then use to make Displayer API calls.

You can use the conversion service in a variety of ways, for example manually in your Web browser, using cURL in a terminal or by making an HTTP request in your application code.

In the Browser

To convert an earner email address to Backpack user ID in the browser, visit:

https://backpack.openbadges.org/displayer/convert/email

Enter the earner email address to convert to their ID - copy the returned ID to use in your Displayer API calls.

backpack-convert

In Code

You can make a REST API request to the convert service in the Mozilla Backpack to convert an earner email to their user ID, which you can then use in your calls to the Displayer API. The URL for the service is the same as the browser version above:

https://backpack.openbadges.org/displayer/convert/email

...presuming you are using the Mozilla hosted Backpack at backpack.openbadges.org

Converting in the Terminal

You can try the endpoint out in a terminal/ command prompt using cURL and/or include it in your website or application code. You need to make a POST request to the convert URL, passing the email address of the earner as a parameter. If successful, the convert service will return some JSON data including the earner's user ID for the Backpack.

If you have an account with the Mozilla hosted Backpack, you can try the conversion on your own email address in a terminal as follows:

$ curl -i -X POST -d "email=your@address.org" https://backpack.openbadges.org/displayer/convert/email

You should see the response in the terminal when you execute this.

Converting in an Application

To use the convert service in a simple node.js app, your code might look something like this:

var express = require("express");
var logfmt = require("logfmt");
var app = express();
var http = require("http");
var bodyParser = require('body-parser');

app.use(logfmt.requestLogger());
app.use(bodyParser.json());

app.get('/', function(req, res) {
	var earnerData = JSON.stringify({
		email: 'earner@example.org'
	});

	var requestOptions = {
		host : 'backpack.openbadges.org', 
		path : '/displayer/convert/email', 
		method : 'POST', 
		headers: {'Content-Type': 'application/json',
			'Content-Length': Buffer.byteLength(earnerData)
		}
	};

	var convertRequest = http.request(requestOptions, function(reqResponse) {
		var response = [];
		reqResponse.setEncoding('utf8');

		//store data
		reqResponse.on('data', function (responseData) {					
			response.push(responseData);
		});

		reqResponse.on('end', function(){
			var recData=JSON.parse(response.join('')); 
			console.log('response: ' + recData);
			res.send(recData);
		});
	});

	convertRequest.on('error', function(e) {
		console.error(e);
	});
	// post the data
	convertRequest.write(earnerData);
	convertRequest.end();
});

For simplicity, we write the response out, but in your own apps you will of course do something with the ID (i.e. use it to query for the earner's badge groups).

Conversion Response

The convert service will respond with either the failure or success details of your conversion attempt. If successful, the response will be 200 OK, with the following JSON structure:

{
    "status": "okay",
    "email": "earner@example.com",
    "userId": 12345
}

You can then build the userId value into your requests to the Displayer API for the earner's badges and badge groups.

The convert service may return either of the following errors:

Earner email not found:

404 Not Found
{
    "status": "missing",
    "error": "Could not find a user by the email address `earner@example.org`"
}

No email parameter included:

400 Bad Request
{
    "status": "invalid",
    "error": "missing `email` parameter"
}

In your application code, you will naturally need to parse the returned JSON data in a way that suits your needs. For the above node.js code, this extended excerpt demonstrates retrieving the user ID to use in Displayer API requests:

var recData=JSON.parse(response.join(''));
var earnerId = recData.userId;//use this in displayer api requests next

Note that the user ID is returned as a number, not a text string.

Querying for Badge Groups

Once you have the earner's Backpack user ID, you can query for their public badge groups. In the Backpack, earners can arrange badges into collections - these collections are modeled as groups in the Displayer API requests. Earners can make a collection/ group public, in which case it can be queried by displayers they have given their email address to.

backpack-collection

You can request a user's public badge groups in a terminal as follows (using the earner's Backpack ID instead of 12345):

curl -i -X GET https://backpack.openbadges.org/displayer/12345/groups.json

In the Web browser:

https://backpack.openbadges.org/displayer/12345/groups.json

In a node.js app:

var express = require("express");
var logfmt = require("logfmt");
var app = express();
var http = require("http");
app.use(logfmt.requestLogger());

app.get('/', function(req, res) {

	var earnerId = 12345;//could be retrieved from convert service

	var requestOptions = {
		host : 'backpack.openbadges.org', 
		path : '/displayer/'+earnerId+'/groups', 
		method : 'GET'
	};

	var displayRequest = http.request(requestOptions, function(reqResponse) {
		var response = [];
		reqResponse.setEncoding('utf8');

		//store data
		reqResponse.on('data', function (responseData) {					
			response.push(responseData);
		});

		reqResponse.on('end', function(){
			var recData=JSON.parse(response.join('')); 
			console.log('response: ' + recData);
			res.send(recData);
		});
	});

	displayRequest.on('error', function(e) {
		console.error(e);
	});
	displayRequest.end();
});

Your own code will differ when storing the earner's user ID following your call to the convert service. The ID is built into the URL for retrieving groups:

<backpack>/displayer/<user-id>/groups

Earner Groups Response

If your request was successful, the Displayer API will respond with 200 OK and some JSON including an array of the earner's public badge groups:

{
    "userId": 12345,
    "groups": [
        {
            "groupId": 67890,
            "name": "My Badge Group",
            "badges": 3
        },
        ...
    ]
}

The response includes the user ID and the groups array. Each group is listed with an ID, name and number of badges. In your application code, you may wish to use all of these data items, however you will definitely need the groupId of any group whose badges you want to display.

The Displayer API may return a 404 Not Found error:

{
    "httpStatus": 404,
    "status": "missing"
}

Querying for Badges in a Group

Once you have the earner's Backpack user ID and the IDs for any groups you are interested in, you can make a request that will provide you with the earner's awarded badges within each specified group.

You can request the badges in a particular group in a terminal as follows (using the earner's Backpack ID instead of 12345 and the group ID instead of 67890):

curl -i -X GET https://backpack.openbadges.org/displayer/12345/group/67890.json

In the Web browser:

https://backpack.openbadges.org/displayer/12345/group/67890.json

In a node.js app:

var express = require("express");
var logfmt = require("logfmt");
var app = express();
var http = require("http");
app.use(logfmt.requestLogger());

app.get('/', function(req, res) {

	var earnerId = 12345;//could be retrieved from convert service
	var  groupId = 67890;//could be retrieved from earner groups request

	var requestOptions = {
		host : 'backpack.openbadges.org', 
		path : '/displayer/'+earnerId+'/group/'+groupId, 
		method : 'GET'
	};

	var displayRequest = http.request(requestOptions, function(reqResponse) {
		var response = [];
		reqResponse.setEncoding('utf8');

		//store data
		reqResponse.on('data', function (responseData) {					
			response.push(responseData);
		});

		reqResponse.on('end', function(){
			var recData=JSON.parse(response.join('')); 
			console.log('response: ' + recData);
			res.send(recData);
		});
	});

	displayRequest.on('error', function(e) {
		console.error(e);
	});
	displayRequest.end();
});

Your own code will differ when storing the earner's user ID following your call to the convert service and group ID following your groups request from the Displayer API. The IDs are built into the URL for retrieving group badges:

<backpack>/displayer/<user-id>/group/<group-id>

Earner Group Badges Response

If your request was successful, the Displayer API will respond with 200 OK and some JSON including an array of the earner's badges within the requested group:

{
    "userId": 12345,
    "groupId": 67890,
    "badges": [
    {
        "lastValidated": "2014-04-28T17:27:22.000Z",
        "hostedUrl": "http://example.org/badge-assertion.json",
        "assertion": {
            "uid": "abcde12345",
            "recipient": "sha256$abcde1345",
            "badge": {
                "name": "Badge Name",
                "description": "Badge description.",
                "image": "https://example.org/badge.png",
                "criteria": "https://example.org/criteria",
                "issuer": {
                    "name": "Issuer Name",
                    "url": "http://issuersite.org",
                    "_location": "http://example.org/issuer-organization.json",
                    "origin": "http://issuersite.org"
                },
                "_location": "http://issuersite.org/badge-class.json"
            },
            "verify": {
                "url": "http://example.org/badge-assertion.json",
                "type": "hosted"
            },
            "issuedOn": 1398705955,
            "_originalRecipient": {
                "identity": "sha256$abcde1345",
                "type": "email",
                "hashed": true
            },
            "issued_on": 1398705955
        },
        "imageUrl": "https://backpack.openbadges.org/images/badge/abcde12345.png"
    },
    ...
    ]
}

The response includes the user ID, group ID and list of badges in the group. Each badge in the array is represented as an assertion, together with validation and location data. You will be able to use this data to verify and display the badges this earner has been awarded, within a website, application or widget.

The Displayer API may return a 404 Not Found error:

{
    "httpStatus": 404,
    "status": "missing"
}

Security

We send the assertion exactly as we received it, without any escaping or sanitization. You will need to carry out context-relevant escaping of any fields you plan on including in output HTML. Read more about Cross Site Scripting at the Open Web Application Security Project site.

Clone this wiki locally
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.