# Ruby

Call Formerie from any Ruby server with `net/http`, from the standard library, with no gem to install. You don't need a Formerie package or an API key: a form's public address is all it takes.

## Submit a form

Save this as `submit.rb`, and run `ruby submit.rb`.

```ruby
require "json"
require "net/http"

runtime_url = ENV.fetch("FORMERIE_RUNTIME_URL", "https://forms.formerie.com")
# Your form. This is the only line that names it.
form = ENV.fetch("FORMERIE_FORM", "acme/contact")

uri = URI("#{runtime_url}/#{form}/submit")
response = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https", open_timeout: 5, read_timeout: 10) do |http|
  http.post(uri.path, JSON.generate(fields: {
    name: "Jane Example",
    email: "jane@example.com",
    message: "Hello from my server"
  }), "Content-Type" => "application/json")
end
result = JSON.parse(response.body)
puts "#{response.code} #{result["ok"] ? result["submissionUid"] : result.dig("error", "code")}"
```

Replace `acme/contact`, on the marked line, with your own handles. A success is HTTP `202`, with a `submissionUid` such as `sub_p6dr8wq2j7tkan`: the answers are stored, and their email is queued. Each sample reads two optional settings from the environment, `FORMERIE_RUNTIME_URL` for a hostname you've connected, and `FORMERIE_FORM` for the handles.

## Before you start

1. [Publish a form](/guides/publish/), and take its workspace and form handles from the **Publish** tab. Your server doesn't need to be in the form's allowed websites.
2. To try things without emailing anyone, create a test key on the form's **Tests** tab, and put it in an environment variable called `FORMERIE_TEST_KEY`:

```ruby
require "json"
require "net/http"

runtime_url = ENV.fetch("FORMERIE_RUNTIME_URL", "https://forms.formerie.com")
# Your form. This is the only line that names it.
form = ENV.fetch("FORMERIE_FORM", "acme/contact")

uri = URI("#{runtime_url}/#{form}/submit")
response = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https", open_timeout: 5, read_timeout: 10) do |http|
  http.post(uri.path, JSON.generate(fields: {
    name: "Jane Example",
    email: "jane@example.com",
    message: "Just a test"
  }), {
    "Content-Type" => "application/json",
    # Keep the key out of your code. A test is stored apart and emails nobody.
    "X-Formerie-Test-Key" => ENV.fetch("FORMERIE_TEST_KEY")
  })
end
result = JSON.parse(response.body)
puts "#{response.code} #{result["ok"] ? result["submissionUid"] : result.dig("error", "code")}"
```

A test comes back as `tst_...`, is stored apart, and emails nobody. A wrong key gets `TEST_KEY_INVALID`, HTTP `401`, and nothing is stored. Remove the header before you go live, since a key left in place files everything as a test. See [Test from a server or CI](/guides/test-your-form/#test-from-a-server-or-ci).

## Check answers without submitting

`validate` checks answers and stores nothing, so you can flag a problem early. It answers `200` when they pass, and `422` with the same errors as a submission when they don't. The final submission always checks the whole form again.

```ruby
require "json"
require "net/http"

def post_json(action, payload)
  runtime_url = ENV.fetch("FORMERIE_RUNTIME_URL", "https://forms.formerie.com")
  # Your form. This is the only line that names it.
  form = ENV.fetch("FORMERIE_FORM", "acme/contact")
  uri = URI("#{runtime_url}/#{form}/#{action}")
  Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https", open_timeout: 5, read_timeout: 10) do |http|
    http.post(uri.path, JSON.generate(payload), "Content-Type" => "application/json")
  end
end

# Checks answers and stores nothing. With no step, only the fields you send are checked.
def check_answers(fields, step: nil)
  payload = step ? { mode: "step", step: step, fields: fields } : { mode: "partial", fields: fields }
  result = JSON.parse(post_json("validate", payload).body)
  return result if result["ok"] || result.dig("error", "code") == "VALIDATION_FAILED"

  raise result.dig("error", "code")
end
```

By default, only the fields you send are checked. Pass a step to check every field in that step instead, on a form with [steps](/guides/multi-step-forms/). A step the form doesn't have gets `BAD_REQUEST`.

## Show errors per field

Answers that fail come back as `VALIDATION_FAILED`, HTTP `422`, and nothing is stored. `error.fields` holds the problems by field, and `error.issues` holds the same ones in order. Each has a `path`, a `code` to match on, and a `message` that's safe to show, in the form's language.

```ruby
require "erb"
require "json"
require "net/http"

def submit_answers(fields)
  runtime_url = ENV.fetch("FORMERIE_RUNTIME_URL", "https://forms.formerie.com")
  # Your form. This is the only line that names it.
  form = ENV.fetch("FORMERIE_FORM", "acme/contact")
  uri = URI("#{runtime_url}/#{form}/submit")
  response = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https", open_timeout: 5, read_timeout: 10) do |http|
    http.post(uri.path, JSON.generate(fields: fields), "Content-Type" => "application/json")
  end
  JSON.parse(response.body)
end

# Finds the visitor's answer for a path such as contact.email, so the form can show it again.
def answer_at(answers, path)
  path.split(".").reduce(answers) { |value, part| value.is_a?(Hash) ? value[part] : nil }.to_s
end

# One input with its answer kept and its first message under it.
def render_field(path, answers, result)
  message = result.dig("error", "fields", path, 0, "message")
  error = message ? %(<p class="error">#{ERB::Util.html_escape(message)}</p>) : ""
  %(<input name="#{ERB::Util.html_escape(path)}" value="#{ERB::Util.html_escape(answer_at(answers, path))}">#{error})
end
```

A field inside a group has a path such as `contact.email`, and one inside a list has `guests[0].email`, so split the path to find its answer. See [Field paths](/guides/validation/#field-paths). Show the visitor's answers again with the messages, escaped, so they only have to fix what's wrong.

## Retry safely

A network failure doesn't tell you whether the submission arrived. So send one `metadata.idempotencyKey` per submission, the same on every retry. Formerie then counts and delivers it once, and answers a repeat with `DUPLICATE_SUBMISSION`, HTTP `409`, which means the first one worked.

```ruby
require "json"
require "net/http"
require "securerandom"

MAX_ATTEMPTS = 3
LONGEST_WAIT = 30
TEMPORARY_CODES = %w[FORM_MAINTENANCE QUEUE_FAILED INTERNAL_ERROR].freeze

# One attempt. Says what happened, and whether another attempt could help.
def send_once(fields, key)
  runtime_url = ENV.fetch("FORMERIE_RUNTIME_URL", "https://forms.formerie.com")
  # Your form. This is the only line that names it.
  form = ENV.fetch("FORMERIE_FORM", "acme/contact")
  uri = URI("#{runtime_url}/#{form}/submit")
  body = JSON.generate(fields: fields, metadata: { idempotencyKey: key })

  begin
    response = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https", open_timeout: 5, read_timeout: 10) do |http|
      # net/http retries some requests by itself, and this loop does that with a wait.
      http.max_retries = 0
      http.post(uri.path, body, "Content-Type" => "application/json")
    end
  rescue SystemCallError, SocketError, IOError, Timeout::Error, OpenSSL::SSL::SSLError
    return { outcome: "retry-later", reason: "network", again: true }
  end
  status = response.code.to_i

  # Only the short-term limit sends Retry-After. A form's own limit can last an hour, so don't wait for it.
  if status == 429
    after = response["Retry-After"]&.match?(/\A\d+\z/) ? response["Retry-After"].to_i : nil
    return { outcome: "retry-later", reason: "rate-limited", after: after, again: !after.nil? && after <= LONGEST_WAIT }
  end

  # Something in front of Formerie may answer without JSON, so look at the status first.
  begin
    result = JSON.parse(response.body)
  rescue JSON::ParserError
    return { outcome: "retry-later", reason: "bad-response", again: [502, 503, 504].include?(status) }
  end

  return { outcome: "accepted", id: result["submissionUid"] } if result["ok"]

  error = result["error"]
  case error["code"]
  when "DUPLICATE_SUBMISSION"
    # The first send worked, and only its answer was lost.
    { outcome: "accepted", duplicate: true }
  when *TEMPORARY_CODES
    { outcome: "retry-later", reason: error["code"], again: true }
  when "VALIDATION_FAILED"
    { outcome: "invalid", code: error["code"], issues: error["issues"] }
  else
    { outcome: "rejected", code: error["code"], message: error["message"] }
  end
end

# One key per submission, the same on every retry. Store it with the answers if you retry later.
def submit_with_retries(fields, key = SecureRandom.uuid)
  (1..MAX_ATTEMPTS).each do |attempt|
    answer = send_once(fields, key)
    again = answer.delete(:again)
    return answer.merge(key: key, attempts: attempt) if !again || attempt == MAX_ATTEMPTS

    backoff = rand * [0.25 * (2**attempt), 4].min
    sleep [answer[:after] || 0, backoff].max
  end
end
```

| Answer | Retry? |
| --- | --- |
| No connection, or a timeout | Yes, with the same key |
| `429` with `Retry-After` | Yes, after that wait, if it's short. The short-term limit answers with `Retry-After: 60` |
| `429` with no `Retry-After` | No. A form's own limit can last an hour, so ask the visitor to try again later |
| `FORM_MAINTENANCE`, `QUEUE_FAILED`, `INTERNAL_ERROR` | Yes, after a short wait |
| `502`, `503` or `504` with no JSON | Yes. Something in front of Formerie answered |
| Any other answer with no JSON | No. Keep the key, and look into it |
| `DUPLICATE_SUBMISSION` | No. Treat it as a success |
| `VALIDATION_FAILED` and any other code | No. The answer won't change |

- The key must be a non-empty string. Anything else is ignored, and there's no repeat check.
- A repeat is noticed for 300 seconds by default, under the form's repeat window. See [What the repeat window covers](/guides/spam-protection/#what-the-repeat-window-covers).
- The check comes first, so a key that went through gets `DUPLICATE_SUBMISSION` even with different answers. Use a new key for each new submission. A key refused for its answers was never accepted, so it can go again once they're fixed.
- A retry after `QUEUE_FAILED` can store a second copy, which you'd see under **Submissions**. It's rare.

## Human verification

If your form requires human verification, use your own keys, with your site in the provider's list of domains and in the form's allowed websites. The widget adds its token to your form. Forward two things:

1. **The token,** as `verificationToken`, taken out of the fields.
2. **The `Origin` of the visitor's request,** because Formerie compares the token's domain with it. A server sends none by itself, and the check then fails with `TURNSTILE_FAILED`.

```ruby
require "json"
require "net/http"

# posted is what your form sent. origin is the Origin header of the visitor's request.
def submit_verified(posted, origin)
  runtime_url = ENV.fetch("FORMERIE_RUNTIME_URL", "https://forms.formerie.com")
  # Your form. This is the only line that names it.
  form = ENV.fetch("FORMERIE_FORM", "acme/contact")
  uri = URI("#{runtime_url}/#{form}/submit")

  fields = posted.dup
  token = fields.delete("cf-turnstile-response")
  headers = { "Content-Type" => "application/json" }
  # Without the visitor's Origin, the provider's hostname can't match, and the check fails.
  headers["Origin"] = origin unless origin.to_s.empty?

  response = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https", open_timeout: 5, read_timeout: 10) do |http|
    http.post(uri.path, JSON.generate(fields: fields, verificationToken: token), headers)
  end
  JSON.parse(response.body)
end
```

An `Origin` that isn't in the form's allowed websites gets `FORBIDDEN_ORIGIN`. Only forward it for this: on any other form, it turns on a check your server doesn't otherwise need. The widget needs JavaScript in the visitor's browser. See [Verification on the server path](/guides/framework-entry-points/#verification-on-the-server-path).

## Spam checks

Hosted pages and embeds send this metadata for you. From your server, send it yourself, or those checks are skipped.

```ruby
require "json"
require "net/http"
require "securerandom"
require "time"

def submit_with_metadata(fields, started_at, visitor_id)
  runtime_url = ENV.fetch("FORMERIE_RUNTIME_URL", "https://forms.formerie.com")
  # Your form. This is the only line that names it.
  form = ENV.fetch("FORMERIE_FORM", "acme/contact")
  uri = URI("#{runtime_url}/#{form}/submit")
  payload = {
    fields: fields,
    metadata: {
      idempotencyKey: SecureRandom.uuid,
      # When the visitor opened the form, for the minimum submit time check.
      startedAt: started_at.utc.iso8601,
      pageUrl: "https://www.example.com/contact",
      # Your own visitor ID, for a limit rule with the deviceToken scope.
      deviceToken: visitor_id
    }
  }
  response = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https", open_timeout: 5, read_timeout: 10) do |http|
    http.post(uri.path, JSON.generate(payload), "Content-Type" => "application/json")
  end
  JSON.parse(response.body)
end
```

| Field | What it's for |
| --- | --- |
| `idempotencyKey` | The repeat check, as above |
| `startedAt` | When the visitor opened the form, as an ISO 8601 time. Sent sooner than the form's minimum, 1 second by default, it gets `SPAM_REJECTED`. Keep the real time from when you showed the form, not the time of this call. One that can't be read skips the check |
| `pageUrl` | The page the form was sent from. Stored only if it's an http or https address |
| `deviceToken` | Your own visitor ID, for a limit per visitor, below |

The hidden field check runs when your form sends that field, and links and human verification run on the server either way. See [Spam and limits](/guides/spam-protection/).

## Limits from your server

Formerie counts visitors by network address, and from here, that's your server's. **Every visitor counts as your server.**

| Limit | Default | From your server |
| --- | --- | --- |
| Per visitor | 30 submissions every 10 minutes | Shared by all your visitors. Raise it before you launch, or leave it empty for no limit, under **Settings**, then **Submission limits** |
| Whole form | 1,000 submissions an hour | The same. On the Free plan, it's also the most a form can accept |
| Short-term | 120 requests a minute for each form from one address | Can't be changed. It's the only one that sends `Retry-After`. `validate` counts here too |

Over any of them, you get `RATE_LIMITED`, HTTP `429`. To keep a limit for each visitor, a rule with the `deviceToken` scope counts by the ID you send, such as a hash of the visitor's address. The app's settings don't offer that rule yet, so [talk to us](https://formerie.com/contact/) to set one up, and keep the whole-form limit, since anyone calling the form directly can change their ID. See [Limits on the server path](/guides/framework-entry-points/#limits-on-the-server-path) for the reasoning, and [Plans and limits](/guides/plans-and-limits/) for monthly counts.

## Rails

This works through the API: the controller reads the visitor's form, and calls Formerie with `net/http`. It was run against a local Formerie backend with Rails 8.1. It answers `202` with the submission's ID, the same status as Formerie with messages by field, or `503` when it can't reach Formerie. Route it with `post "/contact", to: "contact#create"`, and keep Rails' forgery protection on, with `form_with` in your view.

```ruby
require "json"
require "net/http"

class ContactController < ActionController::Base
  def create
    runtime_url = ENV.fetch("FORMERIE_RUNTIME_URL", "https://forms.formerie.com")
    # Your form. This is the only line that names it.
    form = ENV.fetch("FORMERIE_FORM", "acme/contact")
    uri = URI("#{runtime_url}/#{form}/submit")
    # Name the fields you send, so a visitor can't add others.
    fields = params.permit(:name, :email, :message).to_h
    answer = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https", open_timeout: 5, read_timeout: 10) do |http|
      http.max_retries = 0
      http.post(uri.path, JSON.generate(fields: fields), "Content-Type" => "application/json")
    end
    result = JSON.parse(answer.body)

    if result["ok"]
      render json: { id: result["submissionUid"] }, status: :accepted
    else
      errors = (result.dig("error", "fields") || {}).transform_values { |issues| issues.map { |issue| issue["message"] } }
      render json: { code: result.dig("error", "code"), errors: errors }, status: answer.code.to_i
    end
  rescue SystemCallError, SocketError, IOError, Timeout::Error, OpenSSL::SSL::SSLError, JSON::ParserError
    # No connection, a timeout, or an answer that isn't JSON. Keep the visitor's answers on screen.
    render json: { code: "TRY_AGAIN" }, status: :service_unavailable
  end
end
```

## Good to know

- `read_timeout` defaults to 60 seconds, which is long for a page someone's waiting on. Keep `open_timeout` and `read_timeout` on every call.
- Keep test keys and answers out of your logs. A `requestId` in an error, or the `X-Request-Id` header, is what to log and to quote when you ask for help.
- Match on `error.code`, never on the message, since a form can reword its messages and a status can cover several codes. [Error codes](/guides/error-codes/) lists them all.

| With | Note |
| --- | --- |
| Rails' `Origin` | `request.headers["Origin"]`, for human verification. |
| Sinatra | `params` holds the answers, and `request.env["HTTP_ORIGIN"]` the visitor's `Origin`. |

The routes, fields and every error are in the [API reference](/guides/api-reference/).
