How to make a Fly API call from Ruby

Fly has a graphql API available. You can find ways to use it by looking through their CLI's source code.

I recently wanted to automate a Fly API call from a ruby script. And I was not in an environment where I wanted to install the fly CLI.

Here's some code you can steal, it uses Faraday to make a request to Fly's graphql API.

This specific example shows how to delete an existing application.

url = "https://api.fly.io/graphql"
token = YOUR_FLY_TOKEN_HERE

# Query to delete an app
query = <<~GRAPHQL
  mutation($appId: ID!) {
    deleteApp(appId: $appId) {
      organization {
        id
      }
    }
  }
GRAPHQL

headers = {
  "Authorization" => "Bearer #{token}",
  "Content-Type" => "application/json",
}

variables = {
  "appId" => "my-app-name",
}

payload = {
  "query" => query,
  "variables" => variables,
}.to_json

conn = Faraday.new(url: url)
response = conn.post do |req|
  req.headers = headers
  req.body = payload
end

if response.body.include?("errors")
  raise "Failed to delete #{name}: #{response.status}. #{response.body}"
else
  puts response.body
end