You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rails中如何保存HTTP请求结果?及将Curl响应数据存入数据表

Hey there! Let's break this down into two clear, actionable parts: saving your token response data to a Rails database table, and logging all the details of your HTTP request. Here's a step-by-step guide for both:


1. Saving the Token Response to Your Database

First, you'll need a model to store the token data that matches the structure of your API response.

Step 1: Generate the Model

Run this in your terminal to create a UserToken model (feel free to rename it if it makes more sense for your app):

rails generate model UserToken \
  access_token:string \
  public_key:string \
  refresh_token:string \
  live_mode:boolean \
  user_id:integer \
  token_type:string \
  expires_in:integer \
  scope:string

Then run the migration to create the corresponding database table:

rails db:migrate

Step 2: Parse the Response & Save the Data

Update your existing Net::HTTP code to parse the JSON response and persist it to the database. Here's how to adjust your code:

# Your existing request setup
uri = URI("your-api-endpoint-url")
request = Net::HTTP::Post.new(uri)
# Add any required request headers/body (e.g., auth credentials, content type)
request["Content-Type"] = "application/json"
request.body = JSON.generate({ your_request_params: "value" })

req_options = { use_ssl: uri.scheme == "https" }

response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
  http.request(request)
end

# Parse and save the token data
begin
  token_data = JSON.parse(response.body)
  # Create the record—Rails auto-maps JSON keys to your model's columns
  UserToken.create!(token_data)
  puts "Token data saved successfully!"
rescue JSON::ParserError => e
  puts "Failed to parse API response: #{e.message}"
rescue ActiveRecord::RecordInvalid => e
  puts "Failed to save token data: #{e.message}"
end
  • The create! method raises an error if validation fails, so wrapping it in a rescue block helps handle unexpected issues gracefully instead of crashing your app.

2. Saving HTTP Request & Response Details

To log every detail of your Net::HTTP call (request method, URL, headers, body, and response data), create a dedicated RequestLog model.

Step 1: Generate the RequestLog Model

Run this command (we use jsonb for headers if you're on PostgreSQL—it’s great for querying later; if you’re on SQLite, swap jsonb for text):

rails generate model RequestLog \
  request_method:string \
  url:string \
  request_headers:jsonb \
  request_body:text \
  response_status:integer \
  response_headers:jsonb \
  response_body:text

Run the migration:

rails db:migrate

Step 2: Log the Request & Response

Modify your code to collect and save the request/response data right after making the API call:

# Your existing request setup (same as before)
uri = URI("your-api-endpoint-url")
request = Net::HTTP::Post.new(uri)
request["Content-Type"] = "application/json"
request.body = JSON.generate({ your_request_params: "value" })

req_options = { use_ssl: uri.scheme == "https" }

response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
  http.request(request)
end

# Gather all request/response details
log_data = {
  request_method: request.method,
  url: uri.to_s,
  request_headers: request.to_hash, # Converts headers to a hash for jsonb storage
  request_body: request.body,
  response_status: response.code.to_i,
  response_headers: response.to_hash,
  response_body: response.body
}

# Save the log entry
begin
  RequestLog.create!(log_data)
  puts "Request log saved successfully!"
rescue ActiveRecord::RecordInvalid => e
  puts "Failed to save request log: #{e.message}"
end

If you want to connect the saved token to the request that generated it, add an association between the two models:

  1. Add a reference column to user_tokens:
    rails generate migration AddRequestLogToUserTokens request_log:references
    rails db:migrate
    
  2. Update your models to define the association:
    # app/models/user_token.rb
    class UserToken < ApplicationRecord
      belongs_to :request_log
    end
    
    # app/models/request_log.rb
    class RequestLog < ApplicationRecord
      has_one :user_token
    end
    
  3. Update your save code to link the records:
    request_log = RequestLog.create!(log_data)
    UserToken.create!(token_data.merge(request_log: request_log))
    

Important Notes

  • Sensitive Data: Fields like access_token and refresh_token are sensitive. Consider encrypting them with a gem like attr_encrypted to keep them secure in your database.
  • Validation: Add validations to your models (e.g., validates :access_token, presence: true) to ensure data integrity.
  • Cleanup: If you don't need old logs/tokens forever, set up a background job (like with Sidekiq) to delete records after a set period to keep your database lean.

内容的提问来源于stack exchange,提问作者Sebastian Ruiz Perez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:15:10