Skip to content

Instantly share code, notes, and snippets.

@ahukkanen
Created March 25, 2025 14:05
Show Gist options
  • Save ahukkanen/8b4bad76979810aaddaa3e1e19c6dab7 to your computer and use it in GitHub Desktop.
Save ahukkanen/8b4bad76979810aaddaa3e1e19c6dab7 to your computer and use it in GitHub Desktop.
Sample script to test the Decidim API
# frozen_string_literal: true
# This script is for testing the API authentication functionality in PR:
# https://github.com/decidim/decidim/pull/14225
require "net/http"
require "json"
key = "<add your API key here>"
secret = "<add your API secret here>"
# The GraphQL query you want to perform as authenticated
query = "{ session { user { name } } }"
def send_request(req)
uri = req.uri
http = Net::HTTP.new(uri.hostname, uri.port)
http.use_ssl = true if uri.scheme == "https"
http.request(req)
end
puts "Performing authentication request..."
uri = URI.parse("http://localhost:3000/api/sign_in")
req = Net::HTTP::Post.new(uri)
req.set_form_data("api_user[key]" => key, "api_user[secret]" => secret)
res = send_request(req)
if res.code != "200"
puts "Invalid credentials, response code: #{res.code}"
puts "Please make sure your credentials are correct and do not contain any extra characters, such as whitespace."
exit 1
end
auth = res["Authorization"]
puts "Success!"
puts "Bearer token: #{auth.split.last}"
puts "Performing a GraphQL request as authenticated..."
uri = URI.parse("http://localhost:3000/api")
req = Net::HTTP::Post.new(uri)
req["Authorization"] = auth
req.body = { query: query }.to_json
req.content_type = "application/json"
res = send_request(req)
puts "Response code: #{res.code}"
if res.code == "200"
puts "Success!"
puts "Data: #{res.body}"
else
puts "Invalid response from the server, please check logs."
end
puts "Performing sign out request..."
uri = URI.parse("http://localhost:3000/api/sign_out")
req = Net::HTTP::Delete.new(uri)
req["Authorization"] = auth
res = send_request(req)
puts "Response code: #{res.code}"
if res.code == "200"
puts "Success!"
else
puts "Invalid response from the server, please check logs."
end
puts "Confirming the user is signed out..."
uri = URI.parse("http://localhost:3000/api")
req = Net::HTTP::Post.new(uri)
req["Authorization"] = auth
req.body = { query: query }.to_json
req.content_type = "application/json"
res = send_request(req)
puts "Response code: #{res.code}"
if res.code == "200"
puts "Success!"
puts "Data: #{res.body}"
else
puts "Invalid response from the server, please check logs."
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment