summaryrefslogtreecommitdiff
path: root/examples/tapi
blob: 4495a73377de93f6cfd664e59358025b3f35f5cd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#!/usr/bin/ruby
#
#  tapi - Taginfo API
#
#  Example utility for accessing the Taginfo API
#
#  Usage: tapi PATH KEY=VAL KEY=VAL ...
#
#  The tool will send the request to the server, get the JSON result and
#  print it out in an easier to read form.
#
#  You can set the following environment variables (default in brackets):
#    TAGINFO_API_SERVER   [taginfo.openstreetmap.org]
#    TAGINFO_API_PORT     [80]
#    TAGINFO_API_VERSION  [4]
#

require 'rubygems'

require 'net/http'
require 'uri'
require 'json'

API_SERVER  = ENV['TAGINFO_API_SERVER']  || 'taginfo.openstreetmap.org'
API_PORT    = ENV['TAGINFO_API_PORT']    || 80
API_VERSION = ENV['TAGINFO_API_VERSION'] || '4'

def api_call(path, params)
    query = []
    params.each_pair do |k,v|
        query << k + '=' + v
    end
    uri = URI::HTTP.build({
        :host  => API_SERVER,
        :port  => API_PORT,
        :path  => '/api/' + API_VERSION + '/' + path,
        :query => query.join('&')
    })
    STDERR.puts "URI=#{uri}"

    request = Net::HTTP::Get.new(uri.request_uri)
    request['User-Agent'] = 'tapi/1.0 (Taginfo)'
    result = Net::HTTP.start(uri.host, uri.port) do |http|
        http.request(request)
    end
    if result.code != '200'
        STDERR.puts "#{result.code} #{result.message}"
        STDERR.puts result.body
        exit 1
    end

    puts JSON.pretty_generate(JSON.parse(result.body))
end

path = ARGV.shift.sub(%r{^/}, '')

options = {}
ARGV.each do |arg|
    (k, v) = arg.split('=')
    options[k] = v;
end

api_call(path, options)