Make outbound HTTP requests from a function using the fetch API, covering the GET, DELETE, POST, PUT, and PATCH methods with JSON data. Use these snippets when your function needs to call a REST API, whether to read data, submit a form, or update a resource, while running close to the user on Azion’s global network.

Examples

Get

var myHeaders = new Headers();
myHeaders.append("Accept", "application/json; version=3");
myHeaders.append("Authorization", "Token [TOKEN VALUE]");
var requestOptions = {
method: 'GET',
headers: myHeaders,
redirect: 'follow'
};
fetch("https://api.azionapi.net/digital_certificates/", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));

Delete

fetch('https://example.com/delete-item/' + id, {
method: 'DELETE',
})
.then(res => res.text()) // or res.json()
.then(res => console.log(res))

Post

function createNewProfile(profile) {
const formData = new FormData();
formData.append('first_name', profile.firstName);
formData.append('last_name', profile.lastName);
formData.append('email', profile.email);
return fetch('http://example.com/api/v1/registration', {
method: 'POST',
body: formData
}).then(response => response.json())
}
createNewProfile(profile)
.then((json) => {
// handle success
})
.catch(error => error);

Put

const putMethod = {
method: 'PUT', // Method itself
headers: {
'Content-type': 'application/json; charset=UTF-8' // Indicates the content
},
body: JSON.stringify(someData) // We send data in JSON format
}
// make the HTTP put request using fetch api
fetch(url, putMethod)
.then(response => response.json())
.then(data => console.log(data)) // Manipulate the data retrieved back, if we want to do something with it
.catch(err => console.log(err)) // Do something with the error

Patch

const API_URL = 'https://api.azion.net/'
const API_PATH = 'api/v3/'
fetch(API_URL + API_PATH + 'tasks', {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: 'patch',
body: JSON.stringify( { task: task } )
})

How it works

Each example calls fetch() with a URL and an options object whose method field selects the HTTP verb. Request metadata such as authorization tokens and the Content-Type are passed through headers, either as a Headers instance or a plain object, while bodies are sent as FormData or as a JSON string produced by JSON.stringify. The returned promise resolves to a Response, which the snippets read with .then(response => response.json()) or .text() to consume the payload, and .catch() handles any network or parsing error. Running these requests on a distributed architecture keeps the calling logic close to the user.