有馬遼介
有馬遼介

Reputation: 11

Rails API Grape | content-type is not supported

module API
  class Root < Grape::API
    prefix 'api'

    content_type :json, 'application/json'
    format :json
    default_format :json

    rescue_from Grape::Exceptions::ValidationErrors do |e|
      error!({ error: [{ msg: 'card's information is incorrect' }] }, 400)
    end

    rescue_from :all

    mount API::Ver1::Poker
  end
end

This is my API's root. If I request something in JSON format, this API returns correct value. However, if I request something in other formats such as Text or XML, this API returns like below.

{
    "error": "The provided content-type 'text/plain' is not supported."
}

or

{
    "error": "The provided content-type 'application/xml' is not supported."
}

I want to show error message 'cards information is incorrect'.

Why does not the following validation code work?

rescue_from Grape::Exceptions::ValidationErrors do |e|
    error!({ error: [{ msg: 'card's information is incorrect' }] }, 400)
end

Upvotes: 0

Views: 975

Answers (1)

Sampat Badhe
Sampat Badhe

Reputation: 9095

Because you set the content-type to json, so it won't accept any other content-type.

If you wish to support all content-types

  • either remvoe content type:json,'application/json line

OR

  • add all of the 'content-types' you want to support.
    content_type :json, 'application/json'
    content_type :xml, 'application/xml'
    content_type :txt, 'text/plain'
    

Read more about grape API formats

Upvotes: 0

Related Questions