The discussion revolves around creating a custom API route in Discourse that responds to a GET request. Mathieu is having trouble with a GET request route that always returns a 404 error page, whereas a POST request route works fine. After checking the Rails logs, tgxworld suggests that the issue might not be a 404 error, but rather a 200 response with an HTML view instead of the expected JSON response. Mathieu confirms this and explains that the GET request returns an HTML view with header content, while the POST request returns the expected JSON.
Pfaffman suggests that the issue might be an XY problem and encourages Mathieu to describe the actual goal, which is to create a GET request that returns JSON. Finally, david provides the solution, which is to append .json to the end of the route when requesting it, as Discourse returns the Ember app by default. Mathieu is grateful for the answer and notes that this behavior is specific to Discourse and not well-documented.
I’m trying to create a custom API on Discourse for a plugin I’m working on.
I haven’t any problem to create a POST request, but when I try to create one with GET, it all the time returns a 404 error page.
Here is my code.
after_initialize do
module ::MyApiComments
class Engine < ::Rails::Engine
engine_name "myapi_comments"
isolate_namespace MyApiComments
end
end
class MyApiComments::CommentsController < ::ApplicationController
def get_topic_comments
# Some stuff here
render :json => message, :status => 200
end
end
MyApiComments::Engine.routes.draw do
get '/myapi-t/:id' => 'comments#get_topic_comments'
end
Discourse::Application.routes.append do
mount ::MyApiComments::Engine, at: "/"
end
end
When I use post '/myapi-t/:id' => 'comments#get_topic_comments', all works fine. But I absolutely need to use a GET request and I can’t understand why it doesn’t works.
(by the way, I know there is already an API route to get topic posts, but I don’t use it for good reasons :))
Yeah, it seems it is a 200, not a 404 error page, sorry for mistake.
What I’m really getting is an HTML view with header content (logo, nav, etc.), but not a json string with what I asked for (using render :json).
A GET request which returns JSON, as I described on my first message :).
Make a POST requests returns JSON I asked for, the GET one returns HTML. That is my current problem.
Hmm, really nice thing to know :D.
I knew (I’m using it for other things) that the Discourse API needs to end by .json, but on a specific route that I declared myself… Is this documented somewhere?