The fetch api is the most versitile way to make api requests in svelte.
When making your request, you will commonly build a request object by calling:
request = fetch(url, {options})
The url is self explainitory, and the options are a javascript object (hence the squiggle brackets) and can contain the following optional options
method: "GET", "POST", "PUT", "DELETE",
headers: {"Content-Type": "application/json"},
body: JSON.stringify(data),
mode: "cors", "no-cors", "same-origin",
credentials: "include", "same-origin", "omit"
}All of them are optional!
The most common are.. METHOD: HEADERS: BODY:
BODY is likely a JSON string, therefore will need to use JSON.stringify(YOUR DATA)
fetch('https://api.example.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...'
},
body: JSON.stringify({
name: 'John Doe',
email: 'john@example.com',
role: 'admin'
}),
mode: 'cors',
credentials: 'include'
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
If all goes well, you should recieve a response object
status: 200,
statusText: "OK",
ok: true,
headers: Headers {...},
body: ReadableStream
}Promise-based response object
Contains metadata and body methods
The response.ok is very handy. as is !response.ok
The body cannot be looked at directly, it will just say "Readable Stream"
// After calling response.json()
{
id: 123,
success: true,
message: "User created successfully",
data: {
user: {
name: "John Doe",
email: "john@example.com",
role: "admin",
createdAt: "2023-03-19T12:34:56Z"
}
},
meta: {
timestamp: 1679235296,
version: "1.0.0"
}
}
.json() .text() and .blob()
You extract the actual data from the body by using one of these built in covertors
When you expect the body to be in json format, calling .json() will convert the body to a javascript object. So remember, despite the name, this does not return json, but a javascript object!
Audio or Images. A blob is a general purpose object for things other than json, like images or audio clips.
This is for when you want to see the readable stream just as it is. In plain text. It may look like a json file, but it wont function as one. It also may be used to see the Base64 of a blob.