For easier integration we have made a few examples to get you started using the API.
The 3 examples below are "standalone" scripts and can be used for testing purposes.
It is possible to communicate with the API in html and javascript only. This is the easiest and preferred way of using the API.
We have made a javascript class for easier integration with the basic login and resource calls (GET, POST).
This class takes care of the "Cross-origin resource sharing" lack of support in Internet Explorer versions below 10.
Located here: http://api.induct.no/js/jquery.induct_api.js. (requires jQuery)
<fieldset>
<legend>10 last ideas</legend>
<ul id="ideas"></ul>
<button type="button" id="btn_get_ideas">Get ideas</button>
</fieldset>
<hr/>
<fieldset>
<legend>Submit idea</legend>
<form id="idea_form" method="POST" action="">
Title:<br />
<input type="text" id="title" name="title" /><br />
Description:<br />
<textarea id="description" name="description"></textarea>
<br/><br/>
<button type="submit">Submit</button>
</form>
</fieldset>
<hr/>
<fieldset>
<legend>Login user (client side login popup)</legend>
<button type="button" id="btn_login">Login</button>
</fieldset>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script src="https://api.induct.no/js/jquery.induct_api.js"></script>
<script type="text/javascript">
var API_KEY = "YOUR_API_KEY"; // (client id)
// See InductAPI source (jquery.induct_api.js) for more examples of how you can interact with the API.
var api = new InductAPI(API_KEY);
api.ready(function (e, loginStatus) {
console.log('api.ready()');
console.log(loginStatus);
});
api.error(function (e, error) {
alert(error);
});
// If using API to login
api.loginSuccess(function (e, loginStatus) {
console.log('api.loginSuccess()');
console.log(loginStatus);
alert("Login success");
});
api.loginFailed(function (e, error) {
console.log('api.loginFailed()');
console.log(error);
alert("Login failed");
});
// DOM ready
$(function () {
// Setup button for retreiving 10 last ideas
$('#btn_get_ideas').click(function (e) {
api.GET('/initiatives/ideas/?limit=10&q=order by createdAt desc', function (response) {
$('#ideas').empty();
$.each(response, function (i, item) {
var li = '<li>\
<big>' + item.title + '</big><br/>\
<span>By: ' + item.createdBy.firstNameLastName + '</span>\
</li>';
$('#ideas').append(li);
});
});
});
// Setup form to submit an idea
$('#idea_form').submit(function (e) {
e.preventDefault();
var title = $('#title').val();
var description = $('#description').val();
//TODO: Validate input
var idea = {
'title': title,
'description': description
};
api.POST('/initiatives/ideas', idea, function (response) {
//TODO: Check for successful/invalid response
console.log(response);
if (response.error) {
alert('Error: ' + response.errorDescription);
} else {
alert("Submit complete");
}
});
});
$('#btn_login').click(function (e) {
api.login('popup', function (response) {
// Login page takes care of setting authentication cookie
// After successful response from login all calls to API will authenticate using the access token returned from login
console.log(response);
});
});
});
</script>
The php rest client used by this example can be found here http://phphttpclient.com.
This is used as we did not want to spend time on writing a PHP REST "friendly" client
on our own when there are many implementations of that available free and ready for use.
You can of course implement your own client for interacting with the API.
This example is implemented as one single php file, but you should consider splitting the implementation into seperate "handlers".
Example: "login_handler.php", "api_handler.php" etc.
<?php
session_start();
/* --------------------------------------------------------------------------------- */
require_once('./httpful-0.2.0.phar');
/* --------------------------------------------------------------------------------- */
/*
Induct API custom configuration
/* --------------------------------------------------------------------------------- */
// This is your api key/clientId
$api_client_id = 'YOUR_API_KEY';
// Our own application url
$application_url = 'YOUR_APPLICATION_URL';
// Login page
$api_login_url = 'https://community.induct.no/login';
// This must be kept a secret!
$api_client_secret = 'YOUR_APPLICATION_SECRET';
/* --------------------------------------------------------------------------------- */
/* Induct API examples
/* --------------------------------------------------------------------------------- */
// Helper class for interacting with Induct Web API
class InductAPI
{
// Induct API version
const API_VERSION = 'v1';
// Induct API base url
const API_BASE_URL = 'https://api.induct.no';
// Induct API url with your api_key/clientId eg.: https://api.induct.no/v1/3248fh38f9
private $api_url;
private $api_client_id;
private $access_token;
public function __construct($api_client_id) {
$this->api_client_id = $api_client_id;
$this->api_url = self::API_BASE_URL . '/' . self::API_VERSION . '/' . $api_client_id;
}
public function set_access_token($access_token) {
$this->access_token = $access_token;
}
private function add_access_token($request) {
if($this->access_token) {
$request->addHeader('Authorization', 'Bearer ' . $this->access_token);
}
return $request;
}
/**
* Get a resource from Induct Web API
* eg.: /initiatives/ideas or /initiatives/challenges/23
*
* @return data from Induct Web API
*/
public function get($resource) {
$request = \Httpful\Request::get($this->api_url . $resource)
->expectsJson();
$request = $this->add_access_token($request);
$response = $request->send();
return $response->body;
}
// Not used in this example
public function post($resource, $json_data) {
$request = \Httpful\Request::post($this->api_url . $resource)
->sendsJson()
->body($json_data);
$request = $this->add_access_token($request);
$response = $request->send();
return $response->body;
}
}
$api = new InductAPI($api_client_id, $application_url);
// Handle the login
if(isset($_GET["submit-login"])) {
$_SESSION["login_state"] = rand(10000, 99999);
$redirect_url = $api_login_url .
'/?client_id=' . $api_client_id .
'&response_type=code' .
'&redirect_uri=' . $application_url .
'&state=' . $_SESSION["login_state"];
// Redirect user to login page
header('Location: ' . $redirect_url);
exit();
}
// Handle the login response from login page (this login should be in a different php file. eg. login_handler.php)
// This means the login page has redirected the user back to our application
if(isset($_GET["code"]) && isset($_GET["state"])) {
$code = $_GET["code"];
$state = $_GET["state"];
// Now get the access token from the Induct Web API
// setting the timeout for access token to 60 minutes
$access_token_url = '/auth/access_token?code=' . $code .
'&client_secret=' . $api_client_secret .
'&redirect_uri=' . $application_url .
'&timeout=60';
$access_token_obj = $api->get($access_token_url);
$_SESSION['access_token'] = $access_token_obj;
// Redirect user to logged in page (since we are using only this page redirect to the same page..)
header('Location: ' . $_SERVER['PHP_SELF']);
exit();
}
if(isset($_SESSION['access_token'])) {
// This means we are logged in. We can now use our helper class with the access token
$api->set_access_token($_SESSION['access_token']->token);
}
?>
<?php
// Show login form only if we are not logged in
if(!isset($_SESSION['access_token'])) { ?>
<!-- Should be implemented in an another php file! for handling login! -->
<form name="form-login" id="form-login" method="GET" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input name="submit-login" id="submit-login" type="submit" value="Login"/>
</form>
<hr/>
<?php } ?>
<!-- Should be implemented in an another php file! -->
<form name="form-get-ideas" id="form-get-ideas" method="GET" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input name="submit-get-ideas" id="submit-get-ideas" type="submit" value="GET ideas"/>
</form>
<hr/>
<?php
// Show ideas if we have pushed the submit-get-ideas button
if(isset($_GET['submit-get-ideas'])) {
$ideas = $api->get('/initiatives/ideas?limit=10');
?>
<h2>Ideas:</h2>
<table border="1">
<tr>
<th align="left">Title</th>
<th align="left">Description</th>
</tr>
<?php foreach($ideas as $idea) { ?>
<tr>
<td align="left" valign="top"><?php echo $idea->title; ?></td>
<td align="left" valign="top"><?php echo $idea->description; ?></td>
</tr>
<?php } ?>
</table>
<?php } ?>
This example is implemented as one single cshtml file (.NET using some MVC features and shortcuts).
@{
var apiClientId = "YOUR_CLIENT_ID";
var applicationUrl = "YOUR_APPLICATION_URL";
var apiLoginUrl = "https://community.induct.no/login";
var apiBaseUrl = "https://api.induct.no/v1/";
var applicationSecret = "YOUR_APPLICATION_SECRET";
}
@functions{
public string HttpGet(string url) {
var req = WebRequest.Create(url) as HttpWebRequest;
string result = null;
using (HttpWebResponse resp = req.GetResponse() as HttpWebResponse)
{
var reader = new StreamReader(resp.GetResponseStream());
result = reader.ReadToEnd();
}
return result;
}
}
@{
if(Request.QueryString["submit-login"] != null)
{
Session["login_state"] = new Random().Next(10000, 99999).ToString();
var redirectUrl = string.Format("{0}/?client_id={1}&response_type=code&redirect_uri={2}&state={3}",
apiLoginUrl,
apiClientId,
applicationUrl,
Session["login_state"]);
Response.Redirect(redirectUrl, true);
}
if(Request.QueryString["code"] != null && Request.QueryString["state"] != null)
{
//TODO: validate state
var accessTokenUrl = string.Format("{0}{1}/auth/access_token?code={2}&client_secret={3}&redirect_uri={4}&timeout=60",
apiBaseUrl,
apiClientId,
Request.QueryString["code"].ToString(),
applicationSecret,
applicationUrl);
var accessTokenJson = HttpGet(accessTokenUrl);
var accessTokenObj = Json.Decode(accessTokenJson);
Session["access_token"] = accessTokenObj;
Response.Redirect(applicationUrl, true);
}
}
@if(Session["access_token"] == null) {
<form name="form-login" id="form-login" method="GET" action="#">
<input name="submit-login" id="submit-login" type="submit" value="Login"/>
</form>
<hr/>
}
<form name="form-get-ideas" id="form-get-ideas" method="GET" action="#">
<input name="submit-get-ideas" id="submit-get-ideas" type="submit" value="GET ideas"/>
</form>
<hr/>
@if(Request.QueryString["submit-get-ideas"] != null) {
var accessTokenQueryStr = "";
if (Session["access_token"] != null)
{
accessTokenQueryStr = string.Format("&access_token={0}", ((dynamic)Session["access_token"]).token);
}
var ideasJson = HttpGet(string.Format("{0}{1}/initiatives/ideas?limit=10{2}", apiBaseUrl, apiClientId, accessTokenQueryStr));
var ideasObj = Json.Decode(ideasJson);
// Show ideas if we have pushed the "submit-get-ideas" button
<h2>Ideas:</h2>
<table border="1">
<tr>
<th align="left">Title</th>
<th align="left">Description</th>
</tr>
@foreach(dynamic idea in ideasObj) {
<tr>
<td align="left" valign="top">@idea.title</td>
<td align="left" valign="top">@idea.description</td>
</tr>
}
</table>
}
Induct API 1.0
Last API system update:
11/23/2020 8:43:56 AM