How this page was checked: app/services/astro_node.rb was executed with plain ruby 4.0 (no Rails installed) against the in-memory API: the chart, the 10-minute ascendant change and the three errors below are its output. The initializer, controller and Rails.cache calls are Rails glue and were not run.
The key: credentials first, ENV as a fallback
Run bin/rails credentials:edit and add the key under its own namespace. The file is encrypted with config/master.key, which is git-ignored; production needs RAILS_MASTER_KEY set instead. Hosts that only offer environment variables can use ASTRONODE_API_KEY - the initializer accepts either.
Inside bin/rails credentials:edit:
astronode: api_key: aie_live_...
config/initializers/astronode.rb:
ASTRONODE = AstroNode.new(
api_key: Rails.application.credentials.dig(:astronode, :api_key) || ENV["ASTRONODE_API_KEY"],
base_url: ENV.fetch("ASTRONODE_BASE_URL", "https://api.astronode.dev"),
)A Net::HTTP client in app/services
app/services/astro_node.rb - plain Ruby, no Rails dependency:
require "net/http"
require "json"
class AstroNode
class Error < StandardError
attr_reader :status, :code
def initialize(status, code, message)
super("#{status} #{code}: #{message}")
@status = status
@code = code
end
end
def initialize(api_key:, base_url: "https://api.astronode.dev")
@api_key = api_key
@base = URI(base_url)
end
# Divisional chart. division 9 = navamsa (the default), 10 = dasamsa, ...
def varga(birth, division: 9)
post("/v1/charts/varga", birth.merge(division: division))
end
private
def post(path, body)
req = Net::HTTP::Post.new(path, "Authorization" => "Bearer #{@api_key}",
"Content-Type" => "application/json")
req.body = JSON.generate(body)
res = Net::HTTP.start(@base.host, @base.port, use_ssl: @base.scheme == "https",
open_timeout: 5, read_timeout: 15) do |http|
http.request(req)
end
json = JSON.parse(res.body)
unless res.is_a?(Net::HTTPSuccess)
raise Error.new(res.code.to_i, json.dig("error", "code"), json.dig("error", "message"))
end
json.fetch("data")
end
enduse_ssl:is derived from the URL.Net::HTTP.startdoes not switch to TLS on its own because the port is 443; without it the request goes out as plain text to an HTTPS port.read_timeoutdefaults to 60 seconds inNet::HTTP. A Puma thread blocked that long is a thread not serving anyone else, so set it lower.- The class raises one error type carrying the API's
code, so callers can rescueAstroNode::Errorand branch onVALIDATION_ERROR,PLAN_REQUIREDorRATE_LIMITED.
The controller action, cached
app/controllers/navamsa_controller.rb:
class NavamsaController < ApplicationController
def show
birth = {
date: params.require(:date),
time: params.require(:time),
tz_offset_minutes: Integer(params.require(:tz_offset_minutes)),
lat: Float(params.require(:lat)),
lng: Float(params.require(:lng)),
}
division = Integer(params.fetch(:division, 9))
key = ["astronode/varga", division, *birth.values].join(":")
chart = Rails.cache.fetch(key, expires_in: 30.days) do
ASTRONODE.varga(birth, division: division)
end
render json: chart
rescue ArgumentError, TypeError
render json: { error: "bad number in query string" }, status: :bad_request
rescue AstroNode::Error => e
render json: { error: e.code, message: e.message }, status: e.status == 400 ? :bad_request : :bad_gateway
end
endQuery-string values are always strings in Rails, so Integer(...) and Float(...) do the casting - and raise on junk instead of quietly turning "abc" into 0 the way to_i would. Sent as a string, lat came back as 400 VALIDATION_ERROR: Request validation failed.
| Planet | Navamsa sign | House |
|---|---|---|
| Ascendant | Gemini | - |
| Sun | Pisces | 10 |
| Moon | Taurus | 12 |
| Jupiter | Leo | 3 |
| Venus | Virgo | 4 |
| Rahu / Ketu | Aries / Libra | 11 / 5 |
The cache key holds every input, including the minutes of the birth time. A navamsa spans 3°20′ of the zodiac, so the D9 ascendant changes roughly every quarter of an hour of clock time: the same birth at 06:50 returned Cancer, not Gemini. Keying on the date alone would serve one person's chart to another. Thirty days rather than forever lets an engine update reach cached users (divisional charts).
The mistakes that bite first
- "Caching does nothing" in development. The generated
config/environments/development.rbuses:null_storeunlesstmp/caching-dev.txtexists, so everyRails.cache.fetchruns the block. Toggle it withbin/rails dev:cachebefore concluding the cache is broken - and expect every request to hit the API until you do. - A missing master key in production. Without
RAILS_MASTER_KEY(and without the ENV fallback) the credentials lookup returnsnil, the header becomesBearerand every call is401 UNAUTHORIZED: Missing or invalid Authorization header- the exact message the client printed when run with no key. - Unsupported divisions.
division: 13returned400 VALIDATION_ERRORlisting the accepted values: 2, 3, 7, 9, 10, 12, 16, 20, 24, 27, 30, 40, 45 and 60. Passall: trueinstead ofdivisionto get every one of them in one response.
POST /v1/charts/varga needs the Hobby plan or above; a Free key gets 403 PLAN_REQUIRED (what that means).
Questions
- Which AstroNode endpoints does the Ruby on Rails example call?
- 1 endpoint: Divisional Charts (Navamsa, D1-D60) (
POST /v1/charts/varga). - Was the Ruby on Rails code on this page actually run?
app/services/astro_node.rbwas executed with plainruby4.0 (no Rails installed) against the in-memory API: the chart, the 10-minute ascendant change and the three errors below are its output. The initializer, controller andRails.cachecalls are Rails glue and were not run.