Skip to content

Render JSON seems broken it keeps return HTML #219

@HotDudeSmith

Description

@HotDudeSmith

I am new to build Rails API from scratch (only API not web app) so I can build iOS app to connect to API. What I have an issue on my Rails API project doesn't allow me to have return JSON results, it always return HTML. Any idea what is wrong? Any suggestion appreciated. Thanks!

What I want to have a return in JSON like this:
{"code":12,"title":"User doesn't exist","status":404}

This is what I got (it returns in red header in HTML page):
image

Take a look at my scripts:

routes.rb (require JSON format):

Rails.application.routes.draw do

  namespace :api, defaults: { format: :json } do 
    namespace :v1 do
      resources :entries, except: [:new, :edit]
      resources :users, except: [:new, :edit]
    end
  end

end

../app/controllers/api/v1/users_controller.rb

module Api
  module V1
    class UsersController < ApplicationController

      before_action :set_user, only: [:show, :update, :destroy]

      def show
        if User.exists?(params[:id])
          @user = User.find(params[:id])
          render json: @user
        else 
          render json: { code: 12, title: "User doesn't exist", status: 404 }, status: :not_found
      end 
 .
 .
 .

Note: It is very strange how this show method above acting weird. Part 1 is working well to return JSON results but Part 2 returns HTML instead JSON results.

Part 1: render json: @user

Part 2: render json: { code: 12, title: "User doesn't exist", status: 404 }, status: :not_found


../app/controllers/api/v1/application_controller.rb

class ApplicationController < ActionController::API

rescue_from ActionController::ParameterMissing, with: :render_bad_request  
rescue_from ActiveRecord::RecordNotSaved, :with => :access_denied

  def render_bad_request(e)
    render json: params, status: :bad_request
  end

end

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions