Set Up API Endpoints in NuxtJS
Learn about how to set up API endpoints in NuxtJS server.
We'll cover the following...
Just like the pages
directory, the Nuxt server uses file-based routing to set up the API endpoints. That is, a file named hello.ts
would need to be created in the /server/api/
directory in order to create an API endpoint with path /api/hello
.
Preview
The widget below defines four Nuxt API endpoints in the server/api
directory. These endpoints are as follows:
/api/{id}
/api/hello/{id}
/api/hello/?{query_parameters}
/api/hello/{id}/{name}
A page titled test.vue
was created to make requests to each of the test endpoints.
<template> <NuxtLayout> <v-container class="h-100 d-flex flex-column justify-center align-center"> {{ $props.error }} <h1 class="text-center text-h2 w-75">{{ $props?.error?.statusCode }}</h1> <h6 class="text-center text-h4 w-75 mt-5"> {{ $props?.error?.statusMessage }} </h6> <v-container class="w-50 mt-5"> <v-row justify="space-around"> <v-btn to="/admin">Create a Survey</v-btn> <v-btn to="/surveys">Take a Survey</v-btn> </v-row> </v-container> </v-container> </NuxtLayout> </template> <script setup lang="ts"> interface IError { statusCode: string statusMessage: string } interface IErrorProps { error?: IError } const props = defineProps<IErrorProps>() console.log(props) </script>
To test the endpoints in this widget, perform the following tasks:
- Inspect each file in the
server/api
directory. - Inspect the
pages/test.vue
file. - Click the “Run” button to run the widget.
- The endpoint
/api/hello.ts
should be displayed on the successful build of the Nuxt application. - Copy the endpoints into your browser’s URL bar and change the dynamic values to inspect the results. For example, to test the
/api/{id}
endpoint, enter thehttps://ed-5145096084783104.educative.run/api/123
URL into your browser’s address bar. - To view the results from the other endpoint, enter this URL into the browser:
https://ed-5145096084783104.educative.run/test
.
HTTP methods
The /api/hello
endpoint, as specified in the widget above, can receive requests for any given HTTP method (that is, GET
, POST
, PATCH
, PUT
, and DELETE
). However, to specify the exact method for the API endpoint, the file name for the endpoint can be written with this syntax: {ENDPOINT_NAME}.{ENDPOINT_METHOD}.{FILE_EXTENS
...