Below you'll find examples using Fetch API. You can copy paste them in your browser Console to quickly test.
fetch('/posts/1')
.then(response => response.json())
.then(json => console.log(json))
// Output
{
id: 1,
title: '[...]',
body: '[...]',
userId: 1
}
fetch('/posts')
.then(response => response.json())
.then(json => console.log(json))
// Output
[
{ id: 1, title: '[...]' /* ... */ },
/* ... */
{ id: 100, title: '[...]' /* ... */ }
]
fetch('/posts', {
method: 'POST',
body: JSON.stringify({
title: 'foo',
body: 'bar',
userId: 1
}),
headers: {
"Content-type": "application/json; charset=UTF-8"
}
})
.then(response => response.json())
.then(json => console.log(json))
// Output
{
id: 101,
title: 'foo',
body: 'bar',
userId: 1
}
Important: the resource will not be really created on the server but it will be faked as if. In other words, if you try to access a post using 101 as an id, you'll get a 404 error.
fetch('/posts/1', {
method: 'PUT',
body: JSON.stringify({
id: 1,
title: 'foo',
body: 'bar',
userId: 1
}),
headers: {
"Content-type": "application/json; charset=UTF-8"
}
})
.then(response => response.json())
.then(json => console.log(json))
// Output
{
id: 1,
title: 'foo',
body: 'bar',
userId: 1
}
fetch('/posts/1', {
method: 'PATCH',
body: JSON.stringify({
title: 'foo'
}),
headers: {
"Content-type": "application/json; charset=UTF-8"
}
})
.then(response => response.json())
.then(json => console.log(json))
// Output
{
id: 1,
title: 'foo',
body: '[...]',
userId: 1
}
Important: the resource will not be really updated on the server but it will be faked as if.
fetch('/posts/1', {
method: 'DELETE'
})
Important: the resource will not be really deleted on the server but it will be faked as if.
Basic filtering is supported through query parameters.
// Will return all the posts that belong to the first user
fetch('/posts?userId=1')
.then(response => response.json())
.then(json => console.log(json))
One level of nested route is available.
// Equivalent to /comments?postId=1
fetch('/posts/1/comments')
.then(response => response.json())
.then(json => console.log(json))
Available nested routes: