API Endpoints
We’ve covered the +page.svelte
, +page.js
, and +page.server.js
files but we have yet to discuss +server.js
files. These files enable us to accept more than just POST
requests. As web application developers, we may be expected to support various platforms. Having an API simplifies the transmission of data between our server and these other platforms. Many APIs can accept GET and POST requests as well as PUT, PATCH, DELETE, or OPTIONS.
A +server.js
file creates an API endpoint by exporting a function with the name of the HTTP request method you would like for it to accept. The functions exported will take a SvelteKit-specific RequestEvent
parameter and return a Response
object. As an example, we can create a simple endpoint that would allow us to create posts for a blog. This could be useful if we used a mobile app to write and post from. Note that a +server.js
file should not exist alongside page files as it is intended to handle all HTTP request types:
src...