On Sunday, 10 December 2017 19:47:18 UTC+1, Serguei Cambour wrote:
>
> What is the best way to add some API-ish behaviour to a standard Rails
> application ? I mean, is it possible to add some new actions to a
> controller or modify the existing ones so that they return JSON (without
> specifying JSON extension in the URL (like *http://myhost.com/books
> <http://myhost.com/books>* and not *http://myhost.com/books.json
> <http://myhost.com/books.json>* and be able to return either HTML or JSON
> in the same time? Thank you.
>
I think the simplest solution would be to add the following to a new action:
def index
@books = Book.all
render json: @books
end
When trying it with httpi <https://httpie.org> here the response I get:
➜ rails_app git:(master) ✗ http :3000/books
HTTP/1.1 200 OK
Cache-Control: max-age=0, private, must-revalidate
Content-Type: application/json; charset=utf-8
ETag: W/"966ef6fc32020fa85b7250fa20f25208"
Transfer-Encoding: chunked
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-Request-Id: 893c63ac-b9e3-40ee-b8f5-7b9938916ca5
X-Runtime: 0.359281
X-XSS-Protection: 1; mode=block
[
{
"created_at": "2017-12-10T16:06:29.896Z",
"id": 1,
"isbn": "12345",
"title": "Java",
"updated_at": "2017-12-10T16:06:29.896Z"
}
]
--
You received this message because you are subscribed to the Google Groups "Ruby
on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/rubyonrails-talk/b8e93475-e3c7-4d78-b017-eacecbfe1010%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.