Exemplos em JavaScript - Rest APIs
Construa uma requisição GET, DELETE, POST, PUT ou PATCH com dados JSON. Exemplos abaixo:
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 apifetch(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 } )})
Contribuidores