Introduction
CodeProject provides a set of Web APIs to access various resources from the CodeProject web site. There are 2 sets of APIs. One set provides access to articles, messages and questions from CodeProject.com and another set called My API provides access to your own articles, messages, profile, etc. You can read more at https://api.codeproject.com/https://api.codeproject.com.
To start using the API, you have to register at https://www.codeproject.com/script/webapi/userclientregistrations.aspx. When you register, you'll receive a Client ID and a Client Secret required to use the CodeProject API.
The API is protected by OAuth server. You can read more about OAuth protocol at http://oauth.net.
There are 2 steps involved in using the CodeProject API:
- Retrieve an Access Token which has to be sent with each API call.
- Make a call to retrieve the required information.
The CodeProject team provided some examples with the source code but, surprisingly, the source code for the My APIs is missing. So I set out to close this gap. To make things a little bit more interesting, I thought it could be a good idea to use AngularJS. So below I present the function that gets the token and retrieves the user's articles.
$scope.getArticles = function () {
var onGetArticlesComplete = function (response) {
$scope.articles = response.data;
$scope.toggleView = true;
console.log('Articles retrieved successfully');
};
var onGetArticlesError = function (reason) {
alert('Failed to retrieve articles: ' + reason.status + ' ' + reason.statusText);
};
var onGetTokenComplete = function (response) {
appAuthToken = response.data.access_token;
console.log('Token retrieved successfully');
$http({
method: "GET",
url: articlesUrl,
headers: { 'Authorization': 'Bearer ' + appAuthToken }
})
.then(onGetArticlesComplete, onGetArticlesError);
};
var onGetTokenError = function (reason) {
alert('Failed to retrieve the token: ' + reason.status + ' ' + reason.statusText);
};
var postData = $.param({
grant_type: 'password',
client_id: clientId,
client_secret: clientSecret,
username: $scope.user,
password: $scope.password
});
$http({
url: tokenUrl,
method: 'POST',
data: postData
})
.then(onGetTokenComplete, onGetTokenError);
};
The download file contains the complete JavaScript code and the HTML file to show the articles. Please don't forget to set a Client ID and a Client Secret in the JavaScript variables:
var clientId = 'client id goes here';
var clientSecret = 'client secret goes here';
Enjoy it!