Web API
What's A Web API?
If someone talked about an API with you, they probably meant a web API (HTTP based requests)
Web APIs help us fetch data and update data within web applications -> Commonly used with automations
What Can We Do With An API?
You can do whatever action the developer exposed (allowed) for you to used
The industry standard can vary between these types of APIs:
Commonly Used Methods:
-
First approach:
- GET -> Used to fetch data from an app
- POST -> Used to create, update and delete from an app, only difference is either in the URL or the payload (body) of the request
-
Second approach:
- GET -> Fetch data
- POST -> Create data
- PATCH / PUT -> Update data
- DELETE -> Delete data
What Kind Of Data Do We Need To Send?
Well that one is a bit tricky, there's no universal answer to this one as different systems require different parameters and data
Most of the time app manufacturers provide some kind of documentation to follow, either by guides or specifications (OpenAPI / Swagger)
Example:
- Method: GET
- Domain: example.com
- URI: /api/v1/users
- FILTER TYPE: URL search parameters
- AVAILABLE FILTERS:
- username? -> Accepts a username (optional)
Example URL without any parameters: https://example.com/api/v1/users
Example URL with parameters: https://example.com/api/v1/users?username=test
Content-Type: JSON (application/json) Possible Results (based on status code):
- 200 -> Success ->
JSON: [{ username: "user", enabled: true, createdOn: "1970-01-01T00:00:00Z" }] - 400 -> Bad request -> Malformed / unsupported request
- 401 -> Not authorized -> User is not authorized to access this data
- 404 -> Not found -> Wrong URI
- 429 -> Too many requests -> Rate limiting measures, try again later
- 500 -> Internal server error -> Something went wrong with your request
To try this code out:
- press F12 / Ctrl + Shift + I / right click the page and select inspect
- Click on the "Console" tab
- Copy the code
- Paste it in the "Console" tab
- Press enter
let fetchedUsers;
fetchUsers()
.then(users => {
fetchedUsers = users; // After running this code, you can use the "fetchedUsers" variable to play with the data you received
// This will be either null or with an array of objects
if (users) {
console.log("Successfully fetched users:", users);
}
else {
console.log("Could not fetch users");
}
});
async function fetchUsers(username) {
const uri = "/api/v1/users";
const params = new URLSearchParams();
let url = window.location.origin + uri;
if (typeof username === 'string' && username.length > 0) { // Get specific user
params.set('username', username);
url += `?${params.toString()}`;
}
try {
const response = await fetch(url);
if (response.status !== 200) {
return console.error(`Request failed with status code: ${response.status}`);
}
const users = await response.json();
return users;
} catch (e) {
return console.trace("Could not use fetch, got error:", e);
}
}