Next.js custom API
Published: 2022-10-31 16:47:52

Custom API with Next.js

Continuing my previous Next.js article. I wanted to post a smaller section about creating your custom API. 
It is very simple and only requires a few steps so you can create your own API and make some of your pages more dynamic.  

Let's say in our case we create a file with random data and this data can be fetched within our application. 
Of course you could use external sources too like SQL etc. but for now I just make my own database with JS.

We start we creating a JS file called `data.js` in the main folder.
(assuming you have some structure already and you start your application based on my previous blog).
We can add any data in here. but I just place something random for now.
My folder will have an array of object. Ensure what ever data will be placed in here the objects need to have an id.

```
export const projects = [
  {
    id: '1',
    title: 'Project1',
    description: 'Lorem ipsum, dolor sit amet consectetur adipisicing elit. Vitae beatae ullam est voluptatum voluptatem incidunt accusantium dicta ad? Quasi necessitatibus at maiores sunt? Doloribus odit, expedita aliquam eius harum ipsa!',
    link: 'https://github.com/SomeonesGithub',
  },
  {
    id: '2',
    title: 'Project2',
    description: 'Lorem ipsum, dolor sit amet consectetur adipisicing elit. Vitae beatae ullam est voluptatum voluptatem incidunt accusantium dicta ad? Quasi necessitatibus at maiores sunt? Doloribus odit, expedita aliquam eius harum ipsa!',
    link: 'https://github.com/SomeonesGithub',
  },
  {
    id: '3',
    title: 'Project3',
    description: 'Lorem ipsum, dolor sit amet consectetur adipisicing elit. Vitae beatae ullam est voluptatum voluptatem incidunt accusantium dicta ad? Quasi necessitatibus at maiores sunt? Doloribus odit, expedita aliquam eius harum ipsa!',
    link: 'https://github.com/Moszio/Meal-Randomizer-App',
  },
]

```

Ones this is done we can move to the next step. 
In your pages folder you can find an other folder called `api` created an other folder within `api` and add a new file called `index.js`. You might have a premade file in there so lets just delete it for now. 

in you index.js we will do 2 things first importing in your data.js file and we create a function that will handle this data.

```
import { projects } from '../../../data'

const handler = (req, res) => {
  res.status(200).json(projects)
}

export default handler

```
in our function we pass in the req, res which will be the request and response we are fetching and parsing to json.
Ones that is done. You can direct to your url and call this data.
In my case it will be http://localhost:3000/api/projects
and there you go you should see your custom api data in your browser.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/85pgkbqn69iwufblf6bz.png)


Now that we have access to all the data. We want to be more specific and only get 1 particular object. This is when id can also come in handy.

Right now if you go to your URL and try to select one of your object with their ID it will throw out an error.
http://localhost:3000/api/projects/1

To fix that we will create a new file in the same `api` folder.
It will have the following naming convention: `[id].js` the bracket notation is essential to ensure our route is dynamic.

Ones you are in this file lets add the following.

```
import { projects } from '../../../data'

const idPointer = ({ query: { id } }, res) => {
  const filtered = projects.filter((project) => project.id === id)

  if (filtered.length > 0) {
    res.status(200).json(filtered[0])
  } else {
    res.status(404).json({ message: `The selected id: ${id} not found!` })
  }
}

export default idPointer
```
Again the data from our data.js file was imported and we create our function that will send a request and response. In our case we destructured the id or you could have done just with 

```
re.query.id
```
The second part of the code is just to ensure if there is an item the data will be returned, but if there is no matching id with the number given in URL then it returns a custom error message.
Make sure to save everything and now you can select API with their id in url.
http://localhost:3000/api/projects/1

or if your try something like 6
http://localhost:3000/api/projects/6

it will throw out an error.

Hope this blog was helpful in your future custom API creation.

Thank you for reading this.