Rails: Respond json data in a controller based on json files

Rails: Respond json data in a controller based on json files

Sometime let’s say you want to be able to reproduce an issue that is happening in the production environment so in case that your service is built as an API and responding in JSON format, maybe you can open that endpoint and download the JSON content and place it locally so you can mock the data locally and test the exact behavior but without the need to do it directly in production, in order to do that you can respond in your controller methods based on a JSON file, and use the code bellow as a reference for that.

Place your json file in the root folder with some format like:
example.json

{
  "response":[
    {
      "id":1,
      "cancelled":false,
      "start_date":"2016-09-26T14:00:00.000-04:00",
      "end_date":"2016-09-26T15:00:00.000-04:00"
    }
  ]
}

If you’re using the rocket_pants gem:

In your controller:


  def index

    file = File.read('patients.json')
    expose JSON.parse(file)["response"]
  end

Without using a gem:
In your controller:


  def index

    file = File.read('example.json')
    render json: JSON.parse(file)
  end
No Comments

Post A Comment