1 # SPDX-License-Identifier: GPL-2.0-only
3 # This file is part of Nominatim. (https://nominatim.org)
5 # Copyright (C) 2023 by the Nominatim developer community.
6 # For a full list of authors see the git log.
8 Subcommand definitions for API calls from the command line.
10 from typing import Mapping, Dict
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.helpers import zoom_to_rank
23 # Do not repeat documentation of subcommand classes.
24 # pylint: disable=C0111
26 LOG = logging.getLogger()
29 ('street', 'housenumber and street'),
30 ('city', 'city, town or village'),
33 ('country', 'country'),
34 ('postalcode', 'postcode')
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')
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)
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,
59 help=("Simplify output geometry."
60 "Parameter is difference tolerance in degrees."))
63 def _run_api(endpoint: str, args: NominatimArgs, params: Mapping[str, object]) -> int:
64 script_file = args.project_dir / 'website' / (endpoint + '.php')
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.")
72 return run_api_script(endpoint, args.project_dir,
73 phpcgi_bin=args.phpcgi_path, params=params)
77 Execute a search query.
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
82 https://nominatim.org/release-docs/latest/api/Search/
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)
92 _add_api_output_arguments(parser)
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')
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')
111 def run(self, args: NominatimArgs) -> int:
112 params: Dict[str, object]
114 params = dict(q=args.query)
116 params = {k: getattr(args, k) for k, _ in STRUCTURED_QUERY if getattr(args, k)}
118 for param, _ in EXTRADATA_PARAMS:
119 if getattr(args, param):
121 for param in ('format', 'countrycodes', 'exclude_place_ids', 'limit', 'viewbox'):
122 if getattr(args, param):
123 params[param] = getattr(args, param)
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
131 params['bounded'] = '1'
133 params['dedupe'] = '0'
135 return _run_api('search', args, params)
139 Execute API reverse query.
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
144 https://nominatim.org/release-docs/latest/api/Reverse/
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)')
160 _add_api_output_arguments(parser)
163 def run(self, args: NominatimArgs) -> int:
164 api = napi.NominatimAPI(args.project_dir)
166 result = api.reverse(napi.Point(args.lon, args.lat),
167 max_rank=zoom_to_rank(args.zoom or 18),
168 layers=args.get_layers(napi.DataLayer.ADDRESS | napi.DataLayer.POI),
169 address_details=True, # needed for display name
170 geometry_output=args.get_geometry_output(),
171 geometry_simplification=args.polygon_threshold)
174 output = api_output.format_result(
175 napi.ReverseResults([result]),
177 {'locales': args.get_locales(api.config.DEFAULT_LANGUAGE),
178 'extratags': args.extratags,
179 'namedetails': args.namedetails,
180 'addressdetails': args.addressdetails})
181 if args.format != 'xml':
182 # reformat the result, so it is pretty-printed
183 json.dump(json.loads(output), sys.stdout, indent=4, ensure_ascii=False)
185 sys.stdout.write(output)
186 sys.stdout.write('\n')
190 LOG.error("Unable to geocode.")
197 Execute API lookup query.
199 This command works exactly the same as if calling the /lookup endpoint on
200 the web API. See the online documentation for more details on the
202 https://nominatim.org/release-docs/latest/api/Lookup/
205 def add_args(self, parser: argparse.ArgumentParser) -> None:
206 group = parser.add_argument_group('Query arguments')
207 group.add_argument('--id', metavar='OSMID',
208 action='append', required=True, dest='ids',
209 help='OSM id to lookup in format <NRW><id> (may be repeated)')
211 _add_api_output_arguments(parser)
214 def run(self, args: NominatimArgs) -> int:
215 api = napi.NominatimAPI(args.project_dir)
217 places = [napi.OsmID(o[0], int(o[1:])) for o in args.ids]
219 results = api.lookup(places,
220 address_details=True, # needed for display name
221 geometry_output=args.get_geometry_output(),
222 geometry_simplification=args.polygon_threshold or 0.0)
224 output = api_output.format_result(
227 {'locales': args.get_locales(api.config.DEFAULT_LANGUAGE),
228 'extratags': args.extratags,
229 'namedetails': args.namedetails,
230 'addressdetails': args.addressdetails})
231 if args.format != 'xml':
232 # reformat the result, so it is pretty-printed
233 json.dump(json.loads(output), sys.stdout, indent=4, ensure_ascii=False)
235 sys.stdout.write(output)
236 sys.stdout.write('\n')
243 Execute API details query.
245 This command works exactly the same as if calling the /details endpoint on
246 the web API. See the online documentation for more details on the
248 https://nominatim.org/release-docs/latest/api/Details/
251 def add_args(self, parser: argparse.ArgumentParser) -> None:
252 group = parser.add_argument_group('Query arguments')
253 objs = group.add_mutually_exclusive_group(required=True)
254 objs.add_argument('--node', '-n', type=int,
255 help="Look up the OSM node with the given ID.")
256 objs.add_argument('--way', '-w', type=int,
257 help="Look up the OSM way with the given ID.")
258 objs.add_argument('--relation', '-r', type=int,
259 help="Look up the OSM relation with the given ID.")
260 objs.add_argument('--place_id', '-p', type=int,
261 help='Database internal identifier of the OSM object to look up')
262 group.add_argument('--class', dest='object_class',
263 help=("Class type to disambiguated multiple entries "
264 "of the same object."))
266 group = parser.add_argument_group('Output arguments')
267 group.add_argument('--addressdetails', action='store_true',
268 help='Include a breakdown of the address into elements')
269 group.add_argument('--keywords', action='store_true',
270 help='Include a list of name keywords and address keywords')
271 group.add_argument('--linkedplaces', action='store_true',
272 help='Include a details of places that are linked with this one')
273 group.add_argument('--hierarchy', action='store_true',
274 help='Include details of places lower in the address hierarchy')
275 group.add_argument('--group_hierarchy', action='store_true',
276 help='Group the places by type')
277 group.add_argument('--polygon_geojson', action='store_true',
278 help='Include geometry of result')
279 group.add_argument('--lang', '--accept-language', metavar='LANGS',
280 help='Preferred language order for presenting search results')
283 def run(self, args: NominatimArgs) -> int:
286 place = napi.OsmID('N', args.node, args.object_class)
288 place = napi.OsmID('W', args.way, args.object_class)
290 place = napi.OsmID('R', args.relation, args.object_class)
292 assert args.place_id is not None
293 place = napi.PlaceID(args.place_id)
295 api = napi.NominatimAPI(args.project_dir)
297 result = api.details(place,
298 address_details=args.addressdetails,
299 linked_places=args.linkedplaces,
300 parented_places=args.hierarchy,
301 keywords=args.keywords,
302 geometry_output=napi.GeometryFormat.GEOJSON
303 if args.polygon_geojson
304 else napi.GeometryFormat.NONE)
308 output = api_output.format_result(
311 {'locales': args.get_locales(api.config.DEFAULT_LANGUAGE),
312 'group_hierarchy': args.group_hierarchy})
313 # reformat the result, so it is pretty-printed
314 json.dump(json.loads(output), sys.stdout, indent=4, ensure_ascii=False)
315 sys.stdout.write('\n')
319 LOG.error("Object not found in database.")
325 Execute API status query.
327 This command works exactly the same as if calling the /status endpoint on
328 the web API. See the online documentation for more details on the
330 https://nominatim.org/release-docs/latest/api/Status/
333 def add_args(self, parser: argparse.ArgumentParser) -> None:
334 formats = api_output.list_formats(napi.StatusResult)
335 group = parser.add_argument_group('API parameters')
336 group.add_argument('--format', default=formats[0], choices=formats,
337 help='Format of result')
340 def run(self, args: NominatimArgs) -> int:
341 status = napi.NominatimAPI(args.project_dir).status()
342 print(api_output.format_result(status, args.format, {}))