In this post, I am using REST API to get the feed from a third-party application using client ID and client secret.
Before that, you need to have the Client ID and Client Secret ready which we are going to use in this API call. We are making two calls here. The first call is to fetch the access token and the second call will be using the access token we have got in step 1.
The first method to fetch access token is getFeed() which will internally call getArticles() which, in-turn, calls the getAccessTokenByPost() method for authorization used in getArticles() function.
The feeds you can see as below.
Code Section
HTML
- <div id="feedData"></div>
JavaScript
- <script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
- <script type="text/javascript">
- $(document).ready(function() {
- getFeed()
- });
-
- function getFeed() {
- var clientApiKey = "Client ID";
- var clientSecret = "Client Secret";
- var getTokenUrl = "https://xxx.com/oauth/token";
- var generalApiUrl = "https://xxx.com/v2/content?filter.channels.id=114170&filter.state=published";
-
- var appAuthToken;
- getArticles().then(data => {
- $("#feedData").html("");
- console.log(data);
- if (data) {
- var myHtml = "";
- for (i = 0; i < data.length; i++) {
- myHtml += "<br/><table>";
-
- var images = data[i].images;
- myHtml += "<tr><td><img width='800px' height='300px' src=" + data[i].images[0].image_url + " alt='Image'/></td></tr>";
- myHtml += "<tr><td><h2><b><a href=" + data[i].permalink_url + ">" + data[i].title + "</a><b><h2></td></tr>"
- myHtml += "<tr><td>" + data[i].author.display_name + "</td></tr>"
- myHtml += "<tr><td><h3>" + data[i].summary + "</h3></td></tr>"
- myHtml += "<tr><td></td></tr></table><br/>";
- }
- $("#feedData").html(myHtml);
- } else {
- $("#feedData").html("<b>Failed to Load Articles.</b>");
- };
- })
-
- function getArticles() {
- var dfd = new $.Deferred();
- getAccessTokenByPost().done(function() {
- return $.ajax({
- method: "get",
- url: generalApiUrl,
- contentType: "application/json; charset=utf-8",
- headers: {
- 'Authorization': 'Bearer ' + appAuthToken
- }
- }).done(function(data) {
- dfd.resolve(data.data);
- }).fail(function() {
- dfd.fail();
- });
- });
- return dfd.promise();
- }
-
- function getAccessTokenByPost() {
- if (appAuthToken) {
- alert("using saved Access Token");
- return $.Deferred().resolve().promise();
- } else {
- var postData = {
- grant_type: 'client_credentials',
- client_id: clientApiKey,
- client_secret: clientSecret
- };
- return $.post(getTokenUrl, postData, null, 'json').done(function(data) {
- appAuthToken = data.access_token;
- }).fail(function(jqXHR, status, error) {
- alert("getting Access Token failed.");
- });
- }
- }
- }
- </script>
Here, we are getting the feeds in JSON format which we can later play to display on HTML based on our requirement. I have displayed in HTML table.
Cheers!!