Web Studio is almost here! An enhanced experience to make it easier to create, preview, and collaborate on your website contentLearn More
While you can use the Content Fetch REST API using any programming language or framework, we've provided an official JavaScript SDK so you can integrate Agility CMS into your JavaScript project quick and seamlessly.
The JavaScript SDK can be used within the browser (using NPM or a traditional direct script reference) and it can also be used in server-side node.js apps.
Install the Agility Content Fetch JS SDK package into your project:
> npm install @agility/content-fetch
Import the SDK when you need to use it in your JavaScript file(s):
import agility from '@agility/content-fetch'
Initialize the client with your GUID, API Key, and optionally set isPreview=true
(if you are using a preview API Key). You can retrieve these values from API Keys in Agility.
Then you can use the client to execute requests in a variety of ways:
import agility from '@agility/content-fetch'
const api = agility.getApi({
guid: '046a1a87',
apiKey: 'defaultlive.2b7f3a91559d794bedb688358be5e13af2b1e3ae8cd39e8ed2433bbef5d8d6ac',
isPreview: false
});
//use async to write cleaner code
let contentListResult = await api.getContentList({ referenceName: 'posts', languageCode: 'en-us' });
//do something with the list of posts...
console.log(contentListResult);
//OR use callbacks
api.getContentList({
referenceName: 'posts',
languageCode: 'en-us'
})
.then((contentListResult) => {
console.log(contentListResult);
})
.catch((error) => {
console.error(error);
});
While we highly recommend using an NPM set up for new projects, we understand that there are times where that just isn't feasible. For these cases, you can include the SDK by referencing it in a <script>
tag and then accessing it using the assigned global variable called agility
.
Add a reference to the agility-content-fetch.browser.js file:
<!-- Use a specific version (i.e. 1.1.0) -->
<script type="text/javascript" src="https://unpkg.com/@agility/content-fetch@1.1.0/dist/agility-content-fetch.browser.js"></script>
<!-- Or, Use the latest version -->
<script type="text/javascript" src="https://unpkg.com/@agility/content-fetch@latest/dist/agility-content-fetch.browser.js"></script>
Next, you can access the global variable named agility
, initialize the client, and start making API calls.
var api = agility.getApi({
guid: '046a1a87',
apiKey: 'defaultlive.2b7f3a91559d794bedb688358be5e13af2b1e3ae8cd39e8ed2433bbef5d8d6ac'
})
api.getContentItem({
contentID: 21,
languageCode: 'en-us'
})
.then(function(contentItem) {
//on success
document.querySelector("#siteName").innerHTML = contentItem.fields.siteName;
})
.catch(function(error) {
//on error
console.log(error);
});