|
4 | 4 | require 'uri'
|
5 | 5 | require 'json'
|
6 | 6 |
|
| 7 | +## Example script for retrieving all CoderDojos in Japan |
| 8 | + |
| 9 | +API_URI = URI.parse('https://clubs-api.raspberrypi.org/graphql') |
| 10 | + |
| 11 | +HEADERS = { |
| 12 | + 'accept' => 'application/json', |
| 13 | + 'content-type' => 'application/json' |
| 14 | +} |
| 15 | + |
| 16 | +DOJOS_IN_COUNTRY_QUERY = <<~GRAPHQL |
| 17 | + query ( |
| 18 | + $countryCode: String!, |
| 19 | + $after: String, |
| 20 | + ) { |
| 21 | + clubs( |
| 22 | + after: $after, |
| 23 | + filterBy: { |
| 24 | + countryCode: $countryCode, |
| 25 | + brand: CODERDOJO, |
| 26 | + verified: true |
| 27 | + } |
| 28 | + ) { |
| 29 | + nodes { |
| 30 | + name |
| 31 | + latitude |
| 32 | + longitude |
| 33 | + countryCode |
| 34 | + stage |
| 35 | + urlSlug: url |
| 36 | + startTime |
| 37 | + endTime |
| 38 | + openToPublic |
| 39 | + frequency |
| 40 | + day |
| 41 | + id: uuid |
| 42 | + } |
| 43 | + pageInfo { |
| 44 | + endCursor |
| 45 | + hasNextPage |
| 46 | + } |
| 47 | + } |
| 48 | + } |
| 49 | +GRAPHQL |
| 50 | + |
| 51 | +variables = { |
| 52 | + countryCode: 'JP' |
| 53 | +} |
| 54 | + |
| 55 | +def request_data(variables:) |
| 56 | + req_options = { |
| 57 | + use_ssl: API_URI.scheme == 'https' |
| 58 | + } |
| 59 | + request = Net::HTTP::Post.new(API_URI.request_uri, HEADERS) |
| 60 | + request.body = { query: DOJOS_IN_COUNTRY_QUERY, variables: }.to_json |
| 61 | + |
| 62 | + response = Net::HTTP.start(API_URI.hostname, API_URI.port, req_options) do |http| |
| 63 | + http.request(request) |
| 64 | + end |
| 65 | + |
| 66 | + JSON.parse(response.body, symbolize_names: true)[:data][:clubs] |
| 67 | +end |
| 68 | + |
| 69 | +dojos = [] |
| 70 | + |
| 71 | +loop do |
| 72 | + fetched_data = request_data(variables:) |
| 73 | + |
| 74 | + dojos += fetched_data[:nodes] |
| 75 | + page_info = fetched_data[:pageInfo] |
| 76 | + |
| 77 | + break unless page_info[:hasNextPage] |
| 78 | + |
| 79 | + variables[:after] = page_info[:endCursor] |
| 80 | +end |
| 81 | + |
| 82 | +File.open('dojos_earth.json', 'w') do |file| |
| 83 | + file.puts(JSON.pretty_generate(dojos)) |
| 84 | +end |
| 85 | + |
| 86 | +puts "\nNumber of dojos: #{dojos.length}" |
| 87 | +puts "\nCheck out JSON data you fetched by:" |
| 88 | +puts '$ cat dojos_data.json' |
| 89 | + |
| 90 | +exit |
| 91 | + |
| 92 | +################ |
| 93 | + |
7 | 94 | uri = URI.parse("https://zen.coderdojo.com/api/2.0/dojos")
|
8 | 95 | request = Net::HTTP::Post.new(uri)
|
9 | 96 | request.content_type = "application/json"
|
|
0 commit comments