Template:REST API GET sample code (javascript)
From Linux Web Expert
async function doFetch() {
let url = "https://en.wikipedia.org/w/rest.php/some/path";
let headers = {'Api-User-Agent': 'MediaWiki REST API docs examples/0.1 (https://www.mediawiki.org/wiki/API_talk:REST_API)'}
const rsp = await fetch(url, headers);
const data = await rsp.json();
return data;
}
async function fetchAsync()
{
try {
let result = await doFetch();
console.log(result);
} catch( err ) {
console.error( err.message );
}
}
fetchAsync();
/*
Sample code
*/
async function doFetch() {
let url = "https://test.example/foo";
let headers = {'Api-User-Agent': 'MediaWiki REST API docs examples/0.1 (https://www.mediawiki.org/wiki/API_talk:REST_API)'}
let params = {
'x': '1',
'y': '2'
};
let query = Object.keys(params)
.map(k => k + '=' + encodeURIComponent(params[k]))
.join('&');
url = url + '?' + query;
const rsp = await fetch(url, headers);
const data = await rsp.json();
return data;
}
async function fetchAsync()
{
try {
let result = await doFetch();
console.log(result);
} catch( err ) {
console.error( err.message );
}
}
fetchAsync();
Template documentation
[create]