eolas/zk/1_GET.md

106 lines
2.5 KiB
Markdown
Raw Normal View History

2022-08-04 09:00:04 +01:00
---
2022-08-28 10:37:22 +01:00
categories:
- Programming Languages
tags: [backend, node-js, REST, APIs]
2022-08-04 09:00:04 +01:00
---
2022-08-30 10:00:04 +01:00
# Creating a RESTful API: `GET` requests
2022-08-04 09:00:04 +01:00
With our GET request we will simply return the array of course objects.
We create an [event emitter](Events%20module.md#event-emitters) and listener
that listens for GET requests on a specified port and sends data in response to
requests.
2022-08-04 09:00:04 +01:00
```js
// Return a value as response from specified URI
2022-08-30 10:00:04 +01:00
router.get("/", (req, res) => {
2022-08-28 10:37:22 +01:00
res.send(courses);
});
2022-08-04 09:00:04 +01:00
```
Our server is now set up:
![](/_img/server-listening.png)
2022-08-04 09:00:04 +01:00
> When creating our API this structure of creating handlers for specific routes
> will be iterated. Every endpoint will be specified with
> `[app].[http_request_type]` and followed by a callback.
2022-08-04 09:00:04 +01:00
We can now call the endpoint:
```js
const getAllCourses = async () => {
try {
2022-08-30 10:00:04 +01:00
const resp = await axios.get("http://localhost:3000/api/courses");
2022-08-04 09:00:04 +01:00
console.log(resp.data);
} catch (err) {
console.error(err);
}
};
getAllCourses();
```
2022-08-28 10:37:22 +01:00
Returns:
2022-08-04 09:00:04 +01:00
```js
[
2022-08-30 10:00:04 +01:00
{ id: 1, name: "First course" },
{ id: 2, name: "Second course" },
{ id: 3, name: "Third course" },
2022-08-28 10:37:22 +01:00
];
2022-08-04 09:00:04 +01:00
```
## Parameters
The previous example serves the entire set of our data. But we will also need to
retrieve specific values, we do this by adapting the GET callback to accept
parameters. These parameters will correspond to the specific entry in our main
data array.
2022-08-04 09:00:04 +01:00
2022-08-28 10:37:22 +01:00
```js
2022-08-30 10:00:04 +01:00
router.get("/:id", (req, res) => {
2022-08-04 09:00:04 +01:00
res.send(req.params.id);
});
2022-08-28 10:37:22 +01:00
```
2022-08-04 09:00:04 +01:00
We use the `:` symbol in the URI to indicate that we looking to parse for a
specific value in the data. Now if we call `/api/courses/2`, we will get the
second item in the array.
2022-08-04 09:00:04 +01:00
The block above is the most basic format but we would want to add some kind of
error handling, for example:
2022-08-04 14:00:04 +01:00
```js
2022-08-30 10:00:04 +01:00
router.get("/:id", (req, res) => {
2022-08-04 14:00:04 +01:00
const course = courses.find((c) => c.id === parseInt(req.params.id));
2022-08-30 10:00:04 +01:00
if (!course) res.status(404).send("A course with the given ID was not found");
2022-08-04 14:00:04 +01:00
res.send(course);
});
```
2022-08-04 13:30:04 +01:00
## Queries
Whereas parameters return specific data points, queries don't get data they
aggregate or present the data that is returned in a certain way, such as for
instance applying a search function. We indicate queries with a `?` in our URI.
For example: `/api/posts/2018/1?sortBy=name`. To facilitate a request like this
we have to create a GET path that allows for it:
2022-08-04 13:30:04 +01:00
2022-08-28 10:37:22 +01:00
```js
router.get("/:year/:month", (req, res) => {
2022-08-04 13:30:04 +01:00
res.send(req.query);
})[]();
2022-08-28 10:37:22 +01:00
```
2022-08-04 13:30:04 +01:00
We would get the following back:
2022-08-28 10:37:22 +01:00
```json
2022-08-04 13:30:04 +01:00
{
2022-08-28 10:37:22 +01:00
"sortBy": "name"
2022-08-04 13:30:04 +01:00
}
2022-08-28 10:37:22 +01:00
```
2022-08-04 13:30:04 +01:00
Again a JSON object with key-value pairs is returned.