Controller for API and non-API route at the same time? #1270
-
Hi, Suppose I'm building a traditional, server-side rendered website with a UserController. In the end of a method I would return a view. Now I want to add a REST API. Should I use the same UserController? How would I prevent it from returning a view on the API route? GET /user/1 <-- Returns a view What do you suggest? |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
I think you can create a controller for both routes and return view or json response based on the header content-type or custom key, you could also add a middleware for your api routes that adds a header key. https://preview.adonisjs.com/guides/http/content-negotiation
|
Beta Was this translation helpful? Give feedback.
-
Hey @fishnux! 👋 It's up to you! You can do whatever feels better in your mind. 😋 Generally, you have two approaches:
|
Beta Was this translation helpful? Give feedback.
-
Thank you both! |
Beta Was this translation helpful? Give feedback.
I think you can create a controller for both routes and return view or json response based on the header content-type or custom key, you could also add a middleware for your api routes that adds a header key.
https://preview.adonisjs.com/guides/http/content-negotiation