Fetching Data

Discover the available ways to fetch data using Nuxt.

Nuxt 3 provides various ways of fetching data from an external source via composables. These composables can be used inside the script setup or lifecycle hooks. We can use them to gather data from a back-end service or API, and also server API routes, which we will look at later.

For our main project, we will build an app that will fetch stock images using the Pixabay API. Pixabay is a free site for stock images and we can use the API to perform searches by image type and display in our project. We will also look at many other features, such as filtering and limiting the images we receive back from the API.

Pixabay query string

  1. All requests to the Pixabay API begin with the URL: https://pixabay.com/api/?

  2. Then, we build up a query string to complete the request after the ?. We need an API key, which is required for the request: key=YOUR_API_KEY

  3. This part includes your own personal key, and it allows Pixabay to know which application is making the request. Then, a search term can be added using &q=SEARCH_TERM

  4. Each segment of the URL is separated by the &, and we add the search query such as q=beach. Later, we will take this search term from a form input so the user can perform a search. Leaving a string that looks like this: https://pixabay.com/api/?key=YOUR_API_KEY&q=beach

The useFetch composable

The Pixabey query string can then be used with the useFetch composable:

Get hands-on with 1200+ tech skills courses.