]> git.openstreetmap.org Git - nominatim.git/blob - nominatim/clicmd/api.py
Merge pull request #3020 from lonvia/reverse-api
[nominatim.git] / nominatim / clicmd / api.py
1 # SPDX-License-Identifier: GPL-2.0-only
2 #
3 # This file is part of Nominatim. (https://nominatim.org)
4 #
5 # Copyright (C) 2023 by the Nominatim developer community.
6 # For a full list of authors see the git log.
7 """
8 Subcommand definitions for API calls from the command line.
9 """
10 from typing import Mapping, Dict
11 import argparse
12 import logging
13 import json
14 import sys
15
16 from nominatim.tools.exec_utils import run_api_script
17 from nominatim.errors import UsageError
18 from nominatim.clicmd.args import NominatimArgs
19 import nominatim.api as napi
20 import nominatim.api.v1 as api_output
21 from nominatim.api.v1.server_glue import REVERSE_MAX_RANKS
22
23 # Do not repeat documentation of subcommand classes.
24 # pylint: disable=C0111
25
26 LOG = logging.getLogger()
27
28 STRUCTURED_QUERY = (
29     ('street', 'housenumber and street'),
30     ('city', 'city, town or village'),
31     ('county', 'county'),
32     ('state', 'state'),
33     ('country', 'country'),
34     ('postalcode', 'postcode')
35 )
36
37 EXTRADATA_PARAMS = (
38     ('addressdetails', 'Include a breakdown of the address into elements'),
39     ('extratags', ("Include additional information if available "
40                    "(e.g. wikipedia link, opening hours)")),
41     ('namedetails', 'Include a list of alternative names')
42 )
43
44 def _add_api_output_arguments(parser: argparse.ArgumentParser) -> None:
45     group = parser.add_argument_group('Output arguments')
46     group.add_argument('--format', default='jsonv2',
47                        choices=['xml', 'json', 'jsonv2', 'geojson', 'geocodejson'],
48                        help='Format of result')
49     for name, desc in EXTRADATA_PARAMS:
50         group.add_argument('--' + name, action='store_true', help=desc)
51
52     group.add_argument('--lang', '--accept-language', metavar='LANGS',
53                        help='Preferred language order for presenting search results')
54     group.add_argument('--polygon-output',
55                        choices=['geojson', 'kml', 'svg', 'text'],
56                        help='Output geometry of results as a GeoJSON, KML, SVG or WKT')
57     group.add_argument('--polygon-threshold', type=float, default = 0.0,
58                        metavar='TOLERANCE',
59                        help=("Simplify output geometry."
60                              "Parameter is difference tolerance in degrees."))
61
62
63 def _run_api(endpoint: str, args: NominatimArgs, params: Mapping[str, object]) -> int:
64     script_file = args.project_dir / 'website' / (endpoint + '.php')
65
66     if not script_file.exists():
67         LOG.error("Cannot find API script file.\n\n"
68                   "Make sure to run 'nominatim' from the project directory \n"
69                   "or use the option --project-dir.")
70         raise UsageError("API script not found.")
71
72     return run_api_script(endpoint, args.project_dir,
73                           phpcgi_bin=args.phpcgi_path, params=params)
74
75 class APISearch:
76     """\
77     Execute a search query.
78
79     This command works exactly the same as if calling the /search endpoint on
80     the web API. See the online documentation for more details on the
81     various parameters:
82     https://nominatim.org/release-docs/latest/api/Search/
83     """
84
85     def add_args(self, parser: argparse.ArgumentParser) -> None:
86         group = parser.add_argument_group('Query arguments')
87         group.add_argument('--query',
88                            help='Free-form query string')
89         for name, desc in STRUCTURED_QUERY:
90             group.add_argument('--' + name, help='Structured query: ' + desc)
91
92         _add_api_output_arguments(parser)
93
94         group = parser.add_argument_group('Result limitation')
95         group.add_argument('--countrycodes', metavar='CC,..',
96                            help='Limit search results to one or more countries')
97         group.add_argument('--exclude_place_ids', metavar='ID,..',
98                            help='List of search object to be excluded')
99         group.add_argument('--limit', type=int,
100                            help='Limit the number of returned results')
101         group.add_argument('--viewbox', metavar='X1,Y1,X2,Y2',
102                            help='Preferred area to find search results')
103         group.add_argument('--bounded', action='store_true',
104                            help='Strictly restrict results to viewbox area')
105
106         group = parser.add_argument_group('Other arguments')
107         group.add_argument('--no-dedupe', action='store_false', dest='dedupe',
108                            help='Do not remove duplicates from the result list')
109
110
111     def run(self, args: NominatimArgs) -> int:
112         params: Dict[str, object]
113         if args.query:
114             params = dict(q=args.query)
115         else:
116             params = {k: getattr(args, k) for k, _ in STRUCTURED_QUERY if getattr(args, k)}
117
118         for param, _ in EXTRADATA_PARAMS:
119             if getattr(args, param):
120                 params[param] = '1'
121         for param in ('format', 'countrycodes', 'exclude_place_ids', 'limit', 'viewbox'):
122             if getattr(args, param):
123                 params[param] = getattr(args, param)
124         if args.lang:
125             params['accept-language'] = args.lang
126         if args.polygon_output:
127             params['polygon_' + args.polygon_output] = '1'
128         if args.polygon_threshold:
129             params['polygon_threshold'] = args.polygon_threshold
130         if args.bounded:
131             params['bounded'] = '1'
132         if not args.dedupe:
133             params['dedupe'] = '0'
134
135         return _run_api('search', args, params)
136
137 class APIReverse:
138     """\
139     Execute API reverse query.
140
141     This command works exactly the same as if calling the /reverse endpoint on
142     the web API. See the online documentation for more details on the
143     various parameters:
144     https://nominatim.org/release-docs/latest/api/Reverse/
145     """
146
147     def add_args(self, parser: argparse.ArgumentParser) -> None:
148         group = parser.add_argument_group('Query arguments')
149         group.add_argument('--lat', type=float, required=True,
150                            help='Latitude of coordinate to look up (in WGS84)')
151         group.add_argument('--lon', type=float, required=True,
152                            help='Longitude of coordinate to look up (in WGS84)')
153         group.add_argument('--zoom', type=int,
154                            help='Level of detail required for the address')
155         group.add_argument('--layer', metavar='LAYER',
156                            choices=[n.name.lower() for n in napi.DataLayer if n.name],
157                            action='append', required=False, dest='layers',
158                            help='OSM id to lookup in format <NRW><id> (may be repeated)')
159
160         _add_api_output_arguments(parser)
161
162
163     def run(self, args: NominatimArgs) -> int:
164         api = napi.NominatimAPI(args.project_dir)
165
166         details = napi.LookupDetails(address_details=True, # needed for display name
167                                      geometry_output=args.get_geometry_output(),
168                                      geometry_simplification=args.polygon_threshold or 0.0)
169
170         result = api.reverse(napi.Point(args.lon, args.lat),
171                              REVERSE_MAX_RANKS[max(0, min(18, args.zoom or 18))],
172                              args.get_layers(napi.DataLayer.ADDRESS | napi.DataLayer.POI),
173                              details)
174
175         if result:
176             output = api_output.format_result(
177                         napi.ReverseResults([result]),
178                         args.format,
179                         {'locales': args.get_locales(api.config.DEFAULT_LANGUAGE),
180                          'extratags': args.extratags,
181                          'namedetails': args.namedetails,
182                          'addressdetails': args.addressdetails})
183             if args.format != 'xml':
184                 # reformat the result, so it is pretty-printed
185                 json.dump(json.loads(output), sys.stdout, indent=4, ensure_ascii=False)
186             else:
187                 sys.stdout.write(output)
188             sys.stdout.write('\n')
189
190             return 0
191
192         LOG.error("Unable to geocode.")
193         return 42
194
195
196
197 class APILookup:
198     """\
199     Execute API lookup query.
200
201     This command works exactly the same as if calling the /lookup endpoint on
202     the web API. See the online documentation for more details on the
203     various parameters:
204     https://nominatim.org/release-docs/latest/api/Lookup/
205     """
206
207     def add_args(self, parser: argparse.ArgumentParser) -> None:
208         group = parser.add_argument_group('Query arguments')
209         group.add_argument('--id', metavar='OSMID',
210                            action='append', required=True, dest='ids',
211                            help='OSM id to lookup in format <NRW><id> (may be repeated)')
212
213         _add_api_output_arguments(parser)
214
215
216     def run(self, args: NominatimArgs) -> int:
217         params: Dict[str, object] = dict(osm_ids=','.join(args.ids), format=args.format)
218
219         for param, _ in EXTRADATA_PARAMS:
220             if getattr(args, param):
221                 params[param] = '1'
222         if args.lang:
223             params['accept-language'] = args.lang
224         if args.polygon_output:
225             params['polygon_' + args.polygon_output] = '1'
226         if args.polygon_threshold:
227             params['polygon_threshold'] = args.polygon_threshold
228
229         return _run_api('lookup', args, params)
230
231
232 class APIDetails:
233     """\
234     Execute API details query.
235
236     This command works exactly the same as if calling the /details endpoint on
237     the web API. See the online documentation for more details on the
238     various parameters:
239     https://nominatim.org/release-docs/latest/api/Details/
240     """
241
242     def add_args(self, parser: argparse.ArgumentParser) -> None:
243         group = parser.add_argument_group('Query arguments')
244         objs = group.add_mutually_exclusive_group(required=True)
245         objs.add_argument('--node', '-n', type=int,
246                           help="Look up the OSM node with the given ID.")
247         objs.add_argument('--way', '-w', type=int,
248                           help="Look up the OSM way with the given ID.")
249         objs.add_argument('--relation', '-r', type=int,
250                           help="Look up the OSM relation with the given ID.")
251         objs.add_argument('--place_id', '-p', type=int,
252                           help='Database internal identifier of the OSM object to look up')
253         group.add_argument('--class', dest='object_class',
254                            help=("Class type to disambiguated multiple entries "
255                                  "of the same object."))
256
257         group = parser.add_argument_group('Output arguments')
258         group.add_argument('--addressdetails', action='store_true',
259                            help='Include a breakdown of the address into elements')
260         group.add_argument('--keywords', action='store_true',
261                            help='Include a list of name keywords and address keywords')
262         group.add_argument('--linkedplaces', action='store_true',
263                            help='Include a details of places that are linked with this one')
264         group.add_argument('--hierarchy', action='store_true',
265                            help='Include details of places lower in the address hierarchy')
266         group.add_argument('--group_hierarchy', action='store_true',
267                            help='Group the places by type')
268         group.add_argument('--polygon_geojson', action='store_true',
269                            help='Include geometry of result')
270         group.add_argument('--lang', '--accept-language', metavar='LANGS',
271                            help='Preferred language order for presenting search results')
272
273
274     def run(self, args: NominatimArgs) -> int:
275         place: napi.PlaceRef
276         if args.node:
277             place = napi.OsmID('N', args.node, args.object_class)
278         elif args.way:
279             place = napi.OsmID('W', args.way, args.object_class)
280         elif args.relation:
281             place = napi.OsmID('R', args.relation, args.object_class)
282         else:
283             assert args.place_id is not None
284             place = napi.PlaceID(args.place_id)
285
286         api = napi.NominatimAPI(args.project_dir)
287
288         details = napi.LookupDetails(address_details=args.addressdetails,
289                                      linked_places=args.linkedplaces,
290                                      parented_places=args.hierarchy,
291                                      keywords=args.keywords)
292         if args.polygon_geojson:
293             details.geometry_output = napi.GeometryFormat.GEOJSON
294
295         result = api.lookup(place, details)
296
297         if result:
298             output = api_output.format_result(
299                         result,
300                         'json',
301                         {'locales': args.get_locales(api.config.DEFAULT_LANGUAGE),
302                          'group_hierarchy': args.group_hierarchy})
303             # reformat the result, so it is pretty-printed
304             json.dump(json.loads(output), sys.stdout, indent=4, ensure_ascii=False)
305             sys.stdout.write('\n')
306
307             return 0
308
309         LOG.error("Object not found in database.")
310         return 42
311
312
313 class APIStatus:
314     """
315     Execute API status query.
316
317     This command works exactly the same as if calling the /status endpoint on
318     the web API. See the online documentation for more details on the
319     various parameters:
320     https://nominatim.org/release-docs/latest/api/Status/
321     """
322
323     def add_args(self, parser: argparse.ArgumentParser) -> None:
324         formats = api_output.list_formats(napi.StatusResult)
325         group = parser.add_argument_group('API parameters')
326         group.add_argument('--format', default=formats[0], choices=formats,
327                            help='Format of result')
328
329
330     def run(self, args: NominatimArgs) -> int:
331         status = napi.NominatimAPI(args.project_dir).status()
332         print(api_output.format_result(status, args.format, {}))
333         return 0