File Based API Routes

Learn how we can set up API routes with Nuxt.

The Pixabay API had a base URL of https://pixabay.com/api/. We can add parameters to the end, such as: https://pixabay.com/api/?key=${apiKey}&q=sea

The URL string was how we made requests for the image data we wanted, but how could we handle this with our own Nuxt API? The answer lies in the file-based API routes.

File-based API routes

Once it is completed, we can link our server application to a URL to give us the base URL. The base URL is then extended depending on the type of API we want to build. If we were creating an e-commerce API, we may have URLs such as:

  • https://base-url/product: This URL requests or creates a single product depending on the HTTP request method (GET, POST).

  • https://base-url/products: This URL requests all products.

  • https://base-url/customers: This URL requests all customers.

The file names we create will map to each one of these URL segments. This involves creating a new server directory where we can set up our API routes in two ways:

  • Create a routes directory for our routes. The products.js file inside will create the route of https://base-url/products.

  • Create an api directory. The products.js file inside will create the route of https://base-url/api/products.

The api directory prefix can distinguish an API from regular front-end routes you may have. The contents of the server directory using either directory name approach will automatically create our API routes. This is similar to the pages directory creating the routes for the front end. For the rest of our examples, the api folder option will be used.

The defineEventHandler function

Any of the API route files we create must export a function called defineEventHandler. This handler contains the logic to understand how to handle the request and what to send back as a response. A simple example could be:

Get hands-on with 1200+ tech skills courses.