Next.js Discord

Discord Forum

How do i have more than 1 POST / GET function in an API route?

Answered
Cane di Oropa posted this in #help-forum
Open in Discord
Cane di OropaOP
For example app/api/api-a/route.ts, what if I plan to have several functions in this API route /api/api-a ?
Answered by Asian black bear
Querying users is logically always a GET /api/users indeed and search parameters are the way to go whenever you want to filter. Either by naive params such as ?name=foo&age=24 or more complex queries such as ?q=... with a suitable encoding of queries. The former typically is sufficient in 90% of the cases whenever you want to add filtering to any particular resource.
View full answer

14 Replies

Asian black bear
A route can only have one POST handler for example. It logically makes no sense that it has two POST handlers. That's not how REST works.
Cane di OropaOP
Think from the other sides where people want to treat it as a single end point which contains many functions, ntohing to do with how POST works or how REST works
for example, how do we have them in one single file under /api/user/route.ts
export async function registerUser() {}

export async function loginUser() {}

export async function activateUser() {}
Asian black bear
You don't because that's not RESTful
Next's route handlers are exposed as a REST API
You have to map those functions onto proper methods
Or other routes
Cane di OropaOP
You have to map those functions onto proper methods
Or other routes


^ Like how, any example that I could refer?
creating other routes makes absolutely no sense as in we have to create these just to get 3 api routes working /api/user/create-user/route.ts , /api/user/login-user/route.ts, /api/user/activate-user/route.ts
Asian black bear
Because you are not familiar with RESTful API design. Thinking of users as a resource, registering them means creating a new user, as such a POST /api/users is probably the most idiomatic for that. Activating a user means updating an existing record/resource and thus it's likely to end up being a dedicated PATCH /api/users or PUT /api/users request. Personally, the former makes more sense by updating a single flag and setting the record to be active. A login is most likely a POST /api/auth or POST /api/login attempting to create a new session or similar.
Cane di OropaOP
thanks!
appreciate your long post
in short we utilize search query / slug to do more customized functions such as get disabled users, get active users etc in GET method?
Asian black bear
Querying users is logically always a GET /api/users indeed and search parameters are the way to go whenever you want to filter. Either by naive params such as ?name=foo&age=24 or more complex queries such as ?q=... with a suitable encoding of queries. The former typically is sufficient in 90% of the cases whenever you want to add filtering to any particular resource.
Answer