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?
A slightly more expanded explanation for the benefit of the commenter above, since I just had to do this.
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
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With