Next.js Discord

Discord Forum

How to write GET list and GET item in 1 route file?

Answered
Virginia's Warbler posted this in #help-forum
Open in Discord
Virginia's WarblerOP
How can I have 2 GET functions in 1 route.ts file?
One for get all and the other for get 1.
When I wrote like in screenshot, error happened, because I can't gave 2 methods named GET
But then how else can I specify that they are GET methods?
Answered by Brown bear
/api/entries - will return all the item
/api/entries/[id] - will return one item of specific id.
View full answer

13 Replies

Virginia's WarblerOP
Brown bear
You cannot export more than one GET function in one route.ts file.
But you can leverage dynamic routing for this condition.
Brown bear
/api/entries - will return all the item
/api/entries/[id] - will return one item of specific id.
Answer
Virginia's WarblerOP
Ok, so how do I write the code for /api/entries/[id]?
Virginia's WarblerOP
I dont think you understand the main point of my question.

I know the syntax for dynamic routes.
But I want to know how to have both GET all and GET one
So, the 2 GETs cant be in the same file, right?
The GET all should be in entries/route.ts and GET one should be in entries/[id]/route.ts, right?
Virginia's WarblerOP
No, that didnt work. I created a new entries/[entryId]/route.ts and moved the GET one route into there. But that didnt work
Virginia's WarblerOP
@Brown bear ?
I dont think we understood correctly last time.
But here what I got so far https://github.com/Ruslan-Aliyev/Next-Tailwind-Typescript/blob/master/src/app/api/entries/route.ts#L1-L7
My question is: how can I have both GET one and GET all?
Maybe an example would help