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

将API Gateway资源策略输出转为JSON格式及SDK调用结果解析

How to Convert AWS API Gateway Resource Policy to JSON Using Ruby SDK

If you need to fetch an API Gateway resource policy and parse it into a usable JSON object in Ruby, here's a straightforward, practical approach using the AWS SDK for Ruby:

Step 1: Install Required Dependencies

First, make sure you have the necessary gems installed. You'll need the AWS API Gateway SDK and Ruby's built-in JSON parser:

gem install aws-sdk-apigateway json

Step 2: Fetch and Parse the Policy

The get_rest_api method returns the policy as an escaped JSON string—so we need to parse it into a Ruby hash (equivalent to a JSON object) to work with the data. Here's the complete code with explanations:

require 'aws-sdk-apigateway'
require 'json'

# Initialize the API Gateway client
# Credentials are auto-loaded from environment vars, ~/.aws/credentials, or IAM roles (if running on AWS)
client = Aws::APIGateway::Client.new(region: 'us-east-1') # Swap in your AWS region

# Fetch details for your target API
resp = client.get_rest_api({ rest_api_id: "rwxo2fldcl" }) # Replace with your API's ID

# Extract the escaped policy string from the response
policy_string = resp.policy

# Parse the string into a manipulable Ruby hash
parsed_policy = JSON.parse(policy_string)

# Example: Extract and print key policy details
puts "Parsed Policy Details:"
parsed_policy['Statement'].each do |statement|
  puts "- Effect: #{statement['Effect']}, Target Resource: #{statement['Resource']}"
end

Key Tips & Error Handling

  • Credentials Setup: The SDK handles credential management automatically—no need to hardcode keys. Just ensure your environment has valid AWS credentials configured.
  • Missing Policy Check: Some APIs might not have a resource policy attached. Add a check to avoid errors:
  • Parse Safety: Wrap the JSON parse step in a rescue block to handle malformed policy strings:
begin
  resp = client.get_rest_api({ rest_api_id: "rwxo2fldcl" })
  
  if resp.policy.nil?
    puts "This API doesn't have a resource policy attached."
  else
    parsed_policy = JSON.parse(resp.policy)
    # Add your data extraction logic here
  end
rescue Aws::APIGateway::Errors::NotFound => e
  puts "Error: API not found - #{e.message}"
rescue JSON::ParserError => e
  puts "Error: Failed to parse policy - #{e.message}"
end

Extracting Specific Data

Once parsed, you can easily pull out specific values from the policy. For example:

  • Get all allowed actions: parsed_policy['Statement'].map { |s| s['Action'] if s['Effect'] == 'Allow' }.compact
  • List all trusted principals: parsed_policy['Statement'].flat_map { |s| s['Principal'] }

内容的提问来源于stack exchange,提问作者Prashant Shete

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 07:21:43