You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: chapters/interact-apis.qmd
+200-1Lines changed: 200 additions & 1 deletion
Original file line number
Diff line number
Diff line change
@@ -8,5 +8,204 @@ format:
8
8
lightbox: true
9
9
---
10
10
11
-
Now that we know the rudiments of APIs, let's do some exercises to interact with them.
11
+
Now that we understand what an API endpoint is, let's try interacting with the Cat API directly. Enter an endpoint path below (like `/v1/images/search?limit=1`) to see the API response.
12
12
13
+
Try these examples:
14
+
15
+
-`/v1/images/search?limit=1` - Get one random cat image
16
+
-`/v1/images/search?mime_types=gif` - Get a random cat GIF
17
+
-`/v1/breeds` - Get a list of cat breeds
18
+
-`/v1/breeds/siam` - Get information about Siamese cats
19
+
20
+
::: {.callout-note}
21
+
The response will be shown in JSON format, which is a common data format used by APIs. JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate.
In fact, with the same structure, we can interact with multiple APIs. Let's try interacting with [The Metropolitan Museum of Art Collection API](https://metmuseum.github.io/#search) to get the a list of objects ids from the collection.
71
+
72
+
```{ojs}
73
+
74
+
viewof methodParts = Inputs.select(["GET"], {
75
+
label: "HTTP Method",
76
+
attributes: {
77
+
class: "form-select mb-3"
78
+
}
79
+
})
80
+
81
+
viewof domain = Inputs.text({
82
+
label: "Domain",
83
+
placeholder: "collectionapi.metmuseum.org",
84
+
value: "collectionapi.metmuseum.org",
85
+
attributes: {
86
+
class: "form-control mb-3"
87
+
}
88
+
})
89
+
90
+
viewof path = Inputs.text({
91
+
label: "Path",
92
+
placeholder: "/public/collection/v1/search",
93
+
value: "/public/collection/v1/search",
94
+
attributes: {
95
+
class: "form-control mb-3"
96
+
}
97
+
})
98
+
99
+
viewof query = Inputs.text({
100
+
label: "Query parameters",
101
+
placeholder: "?q=cat",
102
+
value: "q=cat",
103
+
attributes: {
104
+
class: "form-control mb-3"
105
+
}
106
+
})
107
+
108
+
async function fetchFromApiParts(method, domain, path, query) {
109
+
const baseUrl = `https://${domain}`;
110
+
const url = `${baseUrl}${path}?${query}`;
111
+
const response = await fetch(url);
112
+
return await response.json();
113
+
}
114
+
115
+
responseParts = {
116
+
const result = await fetchFromApiParts(method, domain, path, query);
0 commit comments