1

I created an rails api to expose my Bottl class. This class has some methods for solving the 99Bottles problem. The song method, for instance, returns the complete lyrics song. My intention is to return a JSON, according to JSON API containing the response of that method.

require_relative '../bottles_logic/bottles'

class SongsController < ApplicationController
  before_action :set_song, only: [:show, :update, :destroy]

  # GET /songs
  def index
    @songs = ::Bottl.new.song

    render json: @songs
  end
end

Using Postman, I get 200 status and the request payload, however, JSON is not shown due to syntax error (unexpected 'S').

My questions are:

  • How to return a JSON according to the JSON API in this case?
  • Do I need to use a Serializer to format this JSON?
  • I'd like to return the lyrics in a json entry called whole_song, so it must be an attribute, right?
4
  • 1
    Hey, can you share the rest of the error log? you should find it in your server logs. thanks! Commented Jul 4, 2018 at 9:49
  • 'Started GET "/songs" for 127.0.0.1 at 2018-07-04 09:22:52 -0300 Processing by SongsController#index as / Completed 200 OK in 1ms (Views: 0.2ms | ActiveRecord: 0.0ms)' Commented Jul 4, 2018 at 12:24
  • Thanks for sharing this part of the log! Do you have a view of the rest of the log? to be precise, the line syntax error (unexpected 'S') and the lines right after? Commented Jul 4, 2018 at 12:31
  • That error is showing up only in Postman "pretty" section. In "Raw" section, I can see the full payload, but it does not render as json Commented Jul 4, 2018 at 12:36

1 Answer 1

5

What data class are you store in @songs? You must pass the hash to render method, for example, render json: { key: value }. If @songs is an object of your class, you must try to use Serializer or @songs.as_json.

Sign up to request clarification or add additional context in comments.

4 Comments

'@songs 'is a String. So is I want it rendered in "whole_song" key, so I have to run render json: { whole_song: '@songs '}, right? Using Serialilzer or' @songs.as_json', I want to have it showed as whole_song attribute. How can I create an atributte?
> So is I want it rendered in "whole_song" key, so I have to run render json: { whole_song: '@songs '}, right? Yes. You do not need to create attribute if @songs is a String. render json: { whole_song: @songs }
It works! Thank you very much! But is it according to JSON API? I think I have to add other fields to the JSON response
The simplest way for you will be adding keys to hash. render json: { whole_song: @songs, album: @album, artist: @artist } Also, you can use local variables instead of instance variables.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.