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.server_glue import REVERSE_MAX_RANKS
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 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)
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),
176 output = api_output.format_result(
177 napi.ReverseResults([result]),
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)
187 sys.stdout.write(output)
188 sys.stdout.write('\n')
192 LOG.error("Unable to geocode.")
199 Execute API lookup query.
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
204 https://nominatim.org/release-docs/latest/api/Lookup/
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)')
213 _add_api_output_arguments(parser)
216 def run(self, args: NominatimArgs) -> int:
217 api = napi.NominatimAPI(args.project_dir)
219 details = napi.LookupDetails(address_details=True, # needed for display name
220 geometry_output=args.get_geometry_output(),
221 geometry_simplification=args.polygon_threshold or 0.0)
223 places = [napi.OsmID(o[0], int(o[1:])) for o in args.ids]
225 results = api.lookup(places, details)
227 output = api_output.format_result(
230 {'locales': args.get_locales(api.config.DEFAULT_LANGUAGE),
231 'extratags': args.extratags,
232 'namedetails': args.namedetails,
233 'addressdetails': args.addressdetails})
234 if args.format != 'xml':
235 # reformat the result, so it is pretty-printed
236 json.dump(json.loads(output), sys.stdout, indent=4, ensure_ascii=False)
238 sys.stdout.write(output)
239 sys.stdout.write('\n')
246 Execute API details query.
248 This command works exactly the same as if calling the /details endpoint on
249 the web API. See the online documentation for more details on the
251 https://nominatim.org/release-docs/latest/api/Details/
254 def add_args(self, parser: argparse.ArgumentParser) -> None:
255 group = parser.add_argument_group('Query arguments')
256 objs = group.add_mutually_exclusive_group(required=True)
257 objs.add_argument('--node', '-n', type=int,
258 help="Look up the OSM node with the given ID.")
259 objs.add_argument('--way', '-w', type=int,
260 help="Look up the OSM way with the given ID.")
261 objs.add_argument('--relation', '-r', type=int,
262 help="Look up the OSM relation with the given ID.")
263 objs.add_argument('--place_id', '-p', type=int,
264 help='Database internal identifier of the OSM object to look up')
265 group.add_argument('--class', dest='object_class',
266 help=("Class type to disambiguated multiple entries "
267 "of the same object."))
269 group = parser.add_argument_group('Output arguments')
270 group.add_argument('--addressdetails', action='store_true',
271 help='Include a breakdown of the address into elements')
272 group.add_argument('--keywords', action='store_true',
273 help='Include a list of name keywords and address keywords')
274 group.add_argument('--linkedplaces', action='store_true',
275 help='Include a details of places that are linked with this one')
276 group.add_argument('--hierarchy', action='store_true',
277 help='Include details of places lower in the address hierarchy')
278 group.add_argument('--group_hierarchy', action='store_true',
279 help='Group the places by type')
280 group.add_argument('--polygon_geojson', action='store_true',
281 help='Include geometry of result')
282 group.add_argument('--lang', '--accept-language', metavar='LANGS',
283 help='Preferred language order for presenting search results')
286 def run(self, args: NominatimArgs) -> int:
289 place = napi.OsmID('N', args.node, args.object_class)
291 place = napi.OsmID('W', args.way, args.object_class)
293 place = napi.OsmID('R', args.relation, args.object_class)
295 assert args.place_id is not None
296 place = napi.PlaceID(args.place_id)
298 api = napi.NominatimAPI(args.project_dir)
300 details = napi.LookupDetails(address_details=args.addressdetails,
301 linked_places=args.linkedplaces,
302 parented_places=args.hierarchy,
303 keywords=args.keywords)
304 if args.polygon_geojson:
305 details.geometry_output = napi.GeometryFormat.GEOJSON
307 result = api.details(place, details)
310 output = api_output.format_result(
313 {'locales': args.get_locales(api.config.DEFAULT_LANGUAGE),
314 'group_hierarchy': args.group_hierarchy})
315 # reformat the result, so it is pretty-printed
316 json.dump(json.loads(output), sys.stdout, indent=4, ensure_ascii=False)
317 sys.stdout.write('\n')
321 LOG.error("Object not found in database.")
327 Execute API status query.
329 This command works exactly the same as if calling the /status endpoint on
330 the web API. See the online documentation for more details on the
332 https://nominatim.org/release-docs/latest/api/Status/
335 def add_args(self, parser: argparse.ArgumentParser) -> None:
336 formats = api_output.list_formats(napi.StatusResult)
337 group = parser.add_argument_group('API parameters')
338 group.add_argument('--format', default=formats[0], choices=formats,
339 help='Format of result')
342 def run(self, args: NominatimArgs) -> int:
343 status = napi.NominatimAPI(args.project_dir).status()
344 print(api_output.format_result(status, args.format, {}))