API stands for an Application programming interface. A fetch API request allows developers to access information from different APIs online and use that information to do something with it. A few methods used during a fetch request are POST, GET, PUT, PATCH, and DELETE. These methods allow you to create, read, update, or delete data that is received with fetch (also known as CRUD).
Here is an example of what the syntax might look like:
fetch('https://example.api/user')
.then(res=>res.json())
.then(data=>console.log(data))
.catch(error=>alert('ERROR'))
Because fetch is promised-based, you can use the .then commands to manage the data found.
In this example :
The first .then is receiving the response and returning it as JSON so that it gets converted to JSON to be read correctly.
The second .then takes that converted JSON data and console logs it so the developer can see what the data looks like. This second .then is where you can modify the data or send it through a function if you wish to do so.
The .catch line is called only when the fetch request fails. An example of this happening is if the data called is not found. If the .catch is called it will alert an error message in this case.
Another example of a fetch request might be more detailed, using a second parameter after the API:
fetch('https://example.api/user',{
method: 'POST',
headers:{
'Content-Type':'application/json'
},
body: JSON.stringify({
name: 'Example'
})
}).then(res=>{
return res.json()
})
.then(data=>console.log(data))
.catch(error=>alert('ERROR'))
In this example, we set the request method as POST. This allows us to get or post the data being requested. To do this we need to:
Set the method to POST.
Fill out the header type, which will be application/json so that it is read correctly.
JSON.stringify the body to convert the value to a JSON string.
The name given to the user, in this case, is 'Example'.
Last the response is returned as JSON so that you can manage the data in the final .then statement.
Another interesting use of fetch is to pull information from a local JSON file.
For example:
fetch("database.json")
.then(res=>res.json())
.then(data=>findData())
.catch(error=>alert('food not found, please enter manually'))
In my last project, I used this method to gather the information from the database I created in my JSON file:
[
{
"food": "life cereal",
"calories": 300,
"type": "meal"
},
{
"food": "eggsalad sandwhich",
"calories": 600,
"type": "meal"
},
{
"food": "BK whopper w/ cheese",
"calories": 790,
"type": "meal"
},
{
"food": "buttered toast",
"calories": 200,
"type": "snack"
},
{
"food": "muffin",
"calories": 400,
"type": "snack"
}
]
In this example, the fetch command pulled my data from my database.json file and sent it to a function called findData(). Once the information was sent to the function I was able to give it a value to check if it existed within the database.json. If the value did not exist in the database, the .catch method will be called. This alerts the user 'food not found, please enter manually'. This was a vital part of my project because, without it, I would have to enter the values manually each time. In addition, I would not have an already existing database that I can fetch to gather or manipulate data.
Troubleshooting an API request
Throughout the labs and my project in which I learned APIs and fetch commands, I came across a few common errors that I think are important to look out for.
The first common error is syntax.
If anything is misspelled it could cause issues in the execution of the fetch, but something I noticed to look out for in particular with the syntax was missing a comma. This could be a very overlooked problem in the fetch command.
For example:
fetch('https://example.api/user',{
method: 'POST',
headers:{
'Content-Type':'application/json'
},
body: JSON.stringify({
name: 'Example'
})
In this code, there must be a comma after the method and headers.
And in this example of my database.json im fetching from:
[
{
"food": "life cereal",
"calories": 300,
"type": "meal"
},
{
"food": "eggsalad sandwhich",
"calories": 600,
"type": "meal"
}
]
In this code, there must be a comma between each object.
These are so small and easy to miss, but crucial to be aware of when troubleshooting an API fetch error.
The second common error I ran across was the type of error you are receiving. It is possible to have a successful fetch(), but also a 404 error. This is because fetch is always considered to be successful unless there is a network error where you can not connect to the server you are fetching from.
This error likely occurs when the index of the URL you are attempting to fetch from is not found. In this example, users/23 does not exist. Interestingly enough a .catch method will not be fired here, because the fetch still technically goes through. I thought this was very important to keep in mind when troubleshooting my fetch errors.
Overall, a fetch API request is by far one of the most useful techniques I have learned so far throughout my coding journey. I will continue to post more useful tips and tricks as I advance my knowledge in the wonderful world of Javascript!