Nuxt.jsRestAPITypescript
Last updated at 2023-10-27

NuxtJS Get Request Parameters in Typescript

ClickUp
Note
AI Status
75%
Last Edit By
Last edited time
Oct 27, 2023 07:08 AM
Metatag
Slug
nuxtjs-request-parameters-typescript
Writer
Published
Published
Date
Oct 27, 2023
Category
Nuxt.js
RestAPI
Typescript
When working with APIs in a Nuxt.js application, it is common to include parameters in GET requests to retrieve specific data.
In this article, we will explore how to handle GET request parameters in a Nuxt.js application using Typescript.

Prerequisites

Before diving into the code examples, make sure you have the following tools installed:
  • Node.js and npm (Node Package Manager)
  • Nuxt.js
  • Typescript
If you haven't installed these tools yet, you can follow the official documentation for each to get started:

Setting up the Project

To get started, let's create a new Nuxt.js project with Typescript support.
Open your terminal and run the following command:
npx create-nuxt-app my-project
Follow the prompts to configure your project.
Make sure to select Typescript as the programming language.

Creating the API Service

Next, we need to create a service that will handle our API requests.
Inside the services directory, create a new file called api.ts.
This file will contain our API service class.
// services/api.ts import axios, { AxiosResponse } from 'axios'; export default class ApiService { private static instance: ApiService; private baseURL: string; private constructor() { this.baseURL = process.env.API_BASE_URL || 'https://api.example.com'; } public static getInstance(): ApiService { if (!ApiService.instance) { ApiService.instance = new ApiService(); } return ApiService.instance; } public async get<T>(url: string, params?: any): Promise<AxiosResponse<T>> { try { const response = await axios.get<T>(`${this.baseURL}${url}`, { params }); return response.data; } catch (error) { throw new Error(`Failed to make GET request to ${url}`); } } }
In the above code, we created a singleton class ApiService with a private constructor to prevent multiple instances.
The getInstance method ensures that we always work with the same instance throughout the application.
The get method is responsible for making the GET request using the Axios library.
It accepts a URL and optional parameters and returns a promise that resolves to the response data.

Using the API Service

Now that we have our API service set up, let's see how to use it to make GET requests with parameters.
In this example, we will retrieve a list of users from an API.
// pages/index.vue <template> <div> <h1>Users</h1> <ul> <li v-for="user in users" :key="user.id">{{ user.name }}</li> </ul> </div> </template> <script lang="ts"> import { Vue, Component } from 'nuxt-property-decorator'; import ApiService from '~/services/api'; interface User { id: number; name: string; } @Component export default class IndexPage extends Vue { private users: User[] = []; async asyncData() { try { const apiService = ApiService.getInstance(); const response = await apiService.get<User[]>('/users', { limit: 10 }); return { users: response }; } catch (error) { console.error(error); } } } </script>
In the above code, we import the ApiService and create an instance of it using the getInstance method.
We then call the get method with the URL and parameters ({ limit: 10 } in this case) to retrieve a list of users.
The response is stored in the users data property, which we can loop over in the template using v-for.

Conclusion

In this article, we learned how to handle GET request parameters in a Nuxt.js application using Typescript.
We created an API service class to handle our requests and used it to retrieve data from an API with parameters.
By following the examples provided, you should now be able to incorporate GET request parameters into your own Nuxt.js projects.

References

Discussion (0)

Related Posts