Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to log API requests in Rails?

I have a Rails application which has an API at /api/v1/...

I would like to be able to log all the requests that are done to the API, and I know they are in the log file, but is there any alternative so that all the requests can be permanently stored?

How do you deal with this in Rails?

like image 859
Hommer Smith Avatar asked May 13 '14 00:05

Hommer Smith


1 Answers

A slightly more expanded explanation for the benefit of the commenter above, since I just had to do this.

  • Create a new model to store each request. This one is called ApiRequest.
class CreateApiRequests < ActiveRecord::Migration[5.2]
  def change
    create_table :api_requests do |t|
      t.belongs_to :api_key
      t.string :endpoint
      t.string :remote_ip
      t.json :payload
      t.datetime :created_at
    end
  end
end
  • Use a "before_action" filter in each API Controller to call a method that will create a new ApiRequest entry and store it.
module Api
  module V2
    class SomeController < ::ApplicationController

      before_action :log_api_request

      <controller methods>

Our application is API-only, so we inherit from the top-level ApplicationController

  • The method log_api_request creates an ApiRequest object as suggested by Carson above.
  def log_api_request
    ApiRequest.create(
      api_key: api_key,
      endpoint: request.fullpath,
      remote_ip: request.remote_ip,
      payload: params,
      created_at: Time.now.iso8601
    )
  end

The gist is to create your own database table/model to log API requests by calling the create consistently from the controller methods as that doesn't require any additional components beyond what's already available.

like image 185
SubbuThePeaceful Avatar answered Oct 26 '22 23:10

SubbuThePeaceful