1 # SPDX-License-Identifier: GPL-2.0-only
3 # This file is part of Nominatim. (https://nominatim.org)
5 # Copyright (C) 2022 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
14 from nominatim.tools.exec_utils import run_api_script
15 from nominatim.errors import UsageError
16 from nominatim.clicmd.args import NominatimArgs
17 from nominatim.api import NominatimAPI
18 from nominatim.apicmd.status import StatusResult
19 import nominatim.result_formatter.v1 as formatting
21 # Do not repeat documentation of subcommand classes.
22 # pylint: disable=C0111
24 LOG = logging.getLogger()
27 ('street', 'housenumber and street'),
28 ('city', 'city, town or village'),
31 ('country', 'country'),
32 ('postalcode', 'postcode')
36 ('addressdetails', 'Include a breakdown of the address into elements'),
37 ('extratags', ("Include additional information if available "
38 "(e.g. wikipedia link, opening hours)")),
39 ('namedetails', 'Include a list of alternative names')
43 ('addressdetails', 'Include a breakdown of the address into elements'),
44 ('keywords', 'Include a list of name keywords and address keywords'),
45 ('linkedplaces', 'Include a details of places that are linked with this one'),
46 ('hierarchy', 'Include details of places lower in the address hierarchy'),
47 ('group_hierarchy', 'Group the places by type'),
48 ('polygon_geojson', 'Include geometry of result')
51 def _add_api_output_arguments(parser: argparse.ArgumentParser) -> None:
52 group = parser.add_argument_group('Output arguments')
53 group.add_argument('--format', default='jsonv2',
54 choices=['xml', 'json', 'jsonv2', 'geojson', 'geocodejson'],
55 help='Format of result')
56 for name, desc in EXTRADATA_PARAMS:
57 group.add_argument('--' + name, action='store_true', help=desc)
59 group.add_argument('--lang', '--accept-language', metavar='LANGS',
60 help='Preferred language order for presenting search results')
61 group.add_argument('--polygon-output',
62 choices=['geojson', 'kml', 'svg', 'text'],
63 help='Output geometry of results as a GeoJSON, KML, SVG or WKT')
64 group.add_argument('--polygon-threshold', type=float, metavar='TOLERANCE',
65 help=("Simplify output geometry."
66 "Parameter is difference tolerance in degrees."))
69 def _run_api(endpoint: str, args: NominatimArgs, params: Mapping[str, object]) -> int:
70 script_file = args.project_dir / 'website' / (endpoint + '.php')
72 if not script_file.exists():
73 LOG.error("Cannot find API script file.\n\n"
74 "Make sure to run 'nominatim' from the project directory \n"
75 "or use the option --project-dir.")
76 raise UsageError("API script not found.")
78 return run_api_script(endpoint, args.project_dir,
79 phpcgi_bin=args.phpcgi_path, params=params)
83 Execute a search query.
85 This command works exactly the same as if calling the /search endpoint on
86 the web API. See the online documentation for more details on the
88 https://nominatim.org/release-docs/latest/api/Search/
91 def add_args(self, parser: argparse.ArgumentParser) -> None:
92 group = parser.add_argument_group('Query arguments')
93 group.add_argument('--query',
94 help='Free-form query string')
95 for name, desc in STRUCTURED_QUERY:
96 group.add_argument('--' + name, help='Structured query: ' + desc)
98 _add_api_output_arguments(parser)
100 group = parser.add_argument_group('Result limitation')
101 group.add_argument('--countrycodes', metavar='CC,..',
102 help='Limit search results to one or more countries')
103 group.add_argument('--exclude_place_ids', metavar='ID,..',
104 help='List of search object to be excluded')
105 group.add_argument('--limit', type=int,
106 help='Limit the number of returned results')
107 group.add_argument('--viewbox', metavar='X1,Y1,X2,Y2',
108 help='Preferred area to find search results')
109 group.add_argument('--bounded', action='store_true',
110 help='Strictly restrict results to viewbox area')
112 group = parser.add_argument_group('Other arguments')
113 group.add_argument('--no-dedupe', action='store_false', dest='dedupe',
114 help='Do not remove duplicates from the result list')
117 def run(self, args: NominatimArgs) -> int:
118 params: Dict[str, object]
120 params = dict(q=args.query)
122 params = {k: getattr(args, k) for k, _ in STRUCTURED_QUERY if getattr(args, k)}
124 for param, _ in EXTRADATA_PARAMS:
125 if getattr(args, param):
127 for param in ('format', 'countrycodes', 'exclude_place_ids', 'limit', 'viewbox'):
128 if getattr(args, param):
129 params[param] = getattr(args, param)
131 params['accept-language'] = args.lang
132 if args.polygon_output:
133 params['polygon_' + args.polygon_output] = '1'
134 if args.polygon_threshold:
135 params['polygon_threshold'] = args.polygon_threshold
137 params['bounded'] = '1'
139 params['dedupe'] = '0'
141 return _run_api('search', args, params)
145 Execute API reverse query.
147 This command works exactly the same as if calling the /reverse endpoint on
148 the web API. See the online documentation for more details on the
150 https://nominatim.org/release-docs/latest/api/Reverse/
153 def add_args(self, parser: argparse.ArgumentParser) -> None:
154 group = parser.add_argument_group('Query arguments')
155 group.add_argument('--lat', type=float, required=True,
156 help='Latitude of coordinate to look up (in WGS84)')
157 group.add_argument('--lon', type=float, required=True,
158 help='Longitude of coordinate to look up (in WGS84)')
159 group.add_argument('--zoom', type=int,
160 help='Level of detail required for the address')
162 _add_api_output_arguments(parser)
165 def run(self, args: NominatimArgs) -> int:
166 params = dict(lat=args.lat, lon=args.lon, format=args.format)
167 if args.zoom is not None:
168 params['zoom'] = args.zoom
170 for param, _ in EXTRADATA_PARAMS:
171 if getattr(args, param):
174 params['accept-language'] = args.lang
175 if args.polygon_output:
176 params['polygon_' + args.polygon_output] = '1'
177 if args.polygon_threshold:
178 params['polygon_threshold'] = args.polygon_threshold
180 return _run_api('reverse', args, params)
185 Execute API lookup query.
187 This command works exactly the same as if calling the /lookup endpoint on
188 the web API. See the online documentation for more details on the
190 https://nominatim.org/release-docs/latest/api/Lookup/
193 def add_args(self, parser: argparse.ArgumentParser) -> None:
194 group = parser.add_argument_group('Query arguments')
195 group.add_argument('--id', metavar='OSMID',
196 action='append', required=True, dest='ids',
197 help='OSM id to lookup in format <NRW><id> (may be repeated)')
199 _add_api_output_arguments(parser)
202 def run(self, args: NominatimArgs) -> int:
203 params: Dict[str, object] = dict(osm_ids=','.join(args.ids), format=args.format)
205 for param, _ in EXTRADATA_PARAMS:
206 if getattr(args, param):
209 params['accept-language'] = args.lang
210 if args.polygon_output:
211 params['polygon_' + args.polygon_output] = '1'
212 if args.polygon_threshold:
213 params['polygon_threshold'] = args.polygon_threshold
215 return _run_api('lookup', args, params)
220 Execute API details query.
222 This command works exactly the same as if calling the /details endpoint on
223 the web API. See the online documentation for more details on the
225 https://nominatim.org/release-docs/latest/api/Details/
228 def add_args(self, parser: argparse.ArgumentParser) -> None:
229 group = parser.add_argument_group('Query arguments')
230 objs = group.add_mutually_exclusive_group(required=True)
231 objs.add_argument('--node', '-n', type=int,
232 help="Look up the OSM node with the given ID.")
233 objs.add_argument('--way', '-w', type=int,
234 help="Look up the OSM way with the given ID.")
235 objs.add_argument('--relation', '-r', type=int,
236 help="Look up the OSM relation with the given ID.")
237 objs.add_argument('--place_id', '-p', type=int,
238 help='Database internal identifier of the OSM object to look up')
239 group.add_argument('--class', dest='object_class',
240 help=("Class type to disambiguated multiple entries "
241 "of the same object."))
243 group = parser.add_argument_group('Output arguments')
244 for name, desc in DETAILS_SWITCHES:
245 group.add_argument('--' + name, action='store_true', help=desc)
246 group.add_argument('--lang', '--accept-language', metavar='LANGS',
247 help='Preferred language order for presenting search results')
250 def run(self, args: NominatimArgs) -> int:
252 params = dict(osmtype='N', osmid=args.node)
254 params = dict(osmtype='W', osmid=args.node)
256 params = dict(osmtype='R', osmid=args.node)
258 params = dict(place_id=args.place_id)
259 if args.object_class:
260 params['class'] = args.object_class
261 for name, _ in DETAILS_SWITCHES:
262 params[name] = '1' if getattr(args, name) else '0'
264 params['accept-language'] = args.lang
266 return _run_api('details', args, params)
271 Execute API status query.
273 This command works exactly the same as if calling the /status endpoint on
274 the web API. See the online documentation for more details on the
276 https://nominatim.org/release-docs/latest/api/Status/
279 def add_args(self, parser: argparse.ArgumentParser) -> None:
280 formats = formatting.create(StatusResult).list_formats()
281 group = parser.add_argument_group('API parameters')
282 group.add_argument('--format', default=formats[0], choices=formats,
283 help='Format of result')
286 def run(self, args: NominatimArgs) -> int:
287 status = NominatimAPI(args.project_dir).status()
288 print(formatting.create(StatusResult).format(status, args.format))