Skip to content

Instantly share code, notes, and snippets.

@marckohlbrugge
Last active October 10, 2022 11:46
  • Star 9 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save marckohlbrugge/7af366e82d7efc630fe68f4d21bfd360 to your computer and use it in GitHub Desktop.
Ruby example of creating a todo and then completing it using wip.co graphql.
# NOTE: Be sure to set the API key further down in the code!
require "net/http"
require "uri"
require "json"
class WIP
def initialize(api_key:)
@api_key = api_key
end
def create_todo(attributes = {})
query = %{
mutation createTodo {
createTodo(input: {#{serialize_attributes(attributes)}}) {
id
body
completed_at
}
}
}
json = make_request query
json["data"]["createTodo"]
end
def complete_todo(todo_id)
query = %{
mutation completeTodo {
completeTodo(id: #{todo_id}) {
id
body
completed_at
}
}
}
json = make_request query
json["data"]["completeTodo"]
end
private
def make_request(query)
uri = URI.parse("https://wip.co/graphql")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
header = {
"Authorization": "bearer #{@api_key}",
"Content-Type": "application/json"
}
request = Net::HTTP::Post.new(uri.request_uri, header)
request.body = { query: query }.to_json
# Send the request
response = http.request(request)
json = JSON.parse(response.body)
if json.has_key? "errors"
raise json["errors"].first["message"]
end
json
end
def serialize_attributes(attributes)
attributes.collect do |k,v|
"#{k}: \"#{v}\""
end.join(", ")
end
end
# Get your API key from wip.co/api
wip = WIP.new(api_key: "REPLACE THIS")
# Create todo
puts "Creating todo…"
todo = wip.create_todo(body:"hello test")
# The ID from the newly created todo
todo_id = todo["id"].to_i
puts "Created! ID: #{todo_id}"
puts "Todo completed_at: #{todo["completed_at"]} (empty)"
# Complete todo
puts "Completing todo with ID: #{todo_id}"
todo = wip.complete_todo(todo_id)
puts "Todo completed_at: #{todo["completed_at"]}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment