Adding an API endpoint for retrieving data
Now we get on to the fun bit: introducing new functionality for the API. In a SvelteKit application, a GET
request is very directly specified by creating a function named GET
inside of a route.
Although we won’t use it for our endpoint, this function has a params
argument that contains the route
parameter. You’ll see this later in the chapter when we implement the PUT
request in the Adding an API endpoint for updating data section.
Valid responses from the endpoint must be proper response objects. We can use SvelteKit’s JSON helper to define a valid JSON response. Error responses are handled by throwing an exception that is built by calling SvelteKit’s error helper. We’ll use both of these now.
The json helper in Node versions below 18
Calls to the json
function may fail with a Response is not defined
error. If you see this error when implementing the following tests, you can install the node...