The WebApi Helpers on the Sxc Controller using Fetch
Modern browsers all support fetch
and this is now the preferred way to get data.
2sxc 13 introduce new JS APIs for this.
Note: If you want to use other AJAX libraries, check out the Bare Metal APIs.
Simple APIs
The simple APIs perform a browser fetch
and return a promise. This is very similar to jQuery.
webApi.fetchRaw(...)
performs a basic fetch and returns a standard promise containing a Response objectwebApi.fetchJson(...)
performs afetch
and returs a promise containing an object which came from JSON recommended
Parameters
All of these methods can be called with just 1 parameter, the url
. But for more control, you can have these parameters:
url
- short api url likecontroller/method?params
or other variations (see below)data
- optional POST data, empty by default. Can be a string or an object. If it's an object, it will auto-convert to JSONmethod
- optional method name, default isGET
, unless you specify data, in which case it defaults toPOST
Url
The url can be any one of these:
- Api URL pointing to a WebAPI of the app - short like
controller/method
or long likeapp/auto/controller/method
- Query url with a query name like
app/auto/query/queryName
- Data url pointing to the data like
app/auto/data/contentType
These can also have parameters like controller/method?id=27
or app/auto/data/contentType/574
depending on what the endpoint expects.
Helper for URLs with Parameters v13
2sxc 13 enhances the webApi.url(...)
function to build a url using a parameters object.
So you can do either one of these examples:
var webApi = $2sxc(moduleId).webApi;
var jsonPromise1 = webApi.fetchJson('blog/rss?category=17');
var jsonPromise2 = webApi.fetchJson(webApi.url('blog/rss', { category: 17 }));
Tutorial
👉 We've updated the simple web api tutorials to demo this
Demo App and further links
You should find some code examples in this demo App
History
- jQuery based
webApi.get(...)
etc. introduced in 2sxc 04.00 - see old docs fetchRaw()
,fetchJson()
,url()
,headers()
API introduced as beta in v12.10- jQuery commands deprecated in v12.10 but will continue to work if the page has jQuery loaded
url(...)
enhanced with parameters object in v12.11fetchRaw(...)
created to fix difficult naming in 12.10;fetch(...)
is now deprecated and will stop working some dayfetchRaw
,fetchJson
,sxc.data(...)
andsxc.query(...)
official for use 13.04