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
18 # Do not repeat documentation of subcommand classes.
19 # pylint: disable=C0111
21 LOG = logging.getLogger()
24 ('street', 'housenumber and street'),
25 ('city', 'city, town or village'),
28 ('country', 'country'),
29 ('postalcode', 'postcode')
33 ('addressdetails', 'Include a breakdown of the address into elements'),
34 ('extratags', ("Include additional information if available "
35 "(e.g. wikipedia link, opening hours)")),
36 ('namedetails', 'Include a list of alternative names')
40 ('addressdetails', 'Include a breakdown of the address into elements'),
41 ('keywords', 'Include a list of name keywords and address keywords'),
42 ('linkedplaces', 'Include a details of places that are linked with this one'),
43 ('hierarchy', 'Include details of places lower in the address hierarchy'),
44 ('group_hierarchy', 'Group the places by type'),
45 ('polygon_geojson', 'Include geometry of result')
48 def _add_api_output_arguments(parser: argparse.ArgumentParser) -> None:
49 group = parser.add_argument_group('Output arguments')
50 group.add_argument('--format', default='jsonv2',
51 choices=['xml', 'json', 'jsonv2', 'geojson', 'geocodejson'],
52 help='Format of result')
53 for name, desc in EXTRADATA_PARAMS:
54 group.add_argument('--' + name, action='store_true', help=desc)
56 group.add_argument('--lang', '--accept-language', metavar='LANGS',
57 help='Preferred language order for presenting search results')
58 group.add_argument('--polygon-output',
59 choices=['geojson', 'kml', 'svg', 'text'],
60 help='Output geometry of results as a GeoJSON, KML, SVG or WKT')
61 group.add_argument('--polygon-threshold', type=float, metavar='TOLERANCE',
62 help=("Simplify output geometry."
63 "Parameter is difference tolerance in degrees."))
66 def _run_api(endpoint: str, args: NominatimArgs, params: Mapping[str, object]) -> int:
67 script_file = args.project_dir / 'website' / (endpoint + '.php')
69 if not script_file.exists():
70 LOG.error("Cannot find API script file.\n\n"
71 "Make sure to run 'nominatim' from the project directory \n"
72 "or use the option --project-dir.")
73 raise UsageError("API script not found.")
75 return run_api_script(endpoint, args.project_dir,
76 phpcgi_bin=args.phpcgi_path, params=params)
80 Execute a search query.
82 This command works exactly the same as if calling the /search endpoint on
83 the web API. See the online documentation for more details on the
85 https://nominatim.org/release-docs/latest/api/Search/
88 def add_args(self, parser: argparse.ArgumentParser) -> None:
89 group = parser.add_argument_group('Query arguments')
90 group.add_argument('--query',
91 help='Free-form query string')
92 for name, desc in STRUCTURED_QUERY:
93 group.add_argument('--' + name, help='Structured query: ' + desc)
95 _add_api_output_arguments(parser)
97 group = parser.add_argument_group('Result limitation')
98 group.add_argument('--countrycodes', metavar='CC,..',
99 help='Limit search results to one or more countries')
100 group.add_argument('--exclude_place_ids', metavar='ID,..',
101 help='List of search object to be excluded')
102 group.add_argument('--limit', type=int,
103 help='Limit the number of returned results')
104 group.add_argument('--viewbox', metavar='X1,Y1,X2,Y2',
105 help='Preferred area to find search results')
106 group.add_argument('--bounded', action='store_true',
107 help='Strictly restrict results to viewbox area')
109 group = parser.add_argument_group('Other arguments')
110 group.add_argument('--no-dedupe', action='store_false', dest='dedupe',
111 help='Do not remove duplicates from the result list')
114 def run(self, args: NominatimArgs) -> int:
115 params: Dict[str, object]
117 params = dict(q=args.query)
119 params = {k: getattr(args, k) for k, _ in STRUCTURED_QUERY if getattr(args, k)}
121 for param, _ in EXTRADATA_PARAMS:
122 if getattr(args, param):
124 for param in ('format', 'countrycodes', 'exclude_place_ids', 'limit', 'viewbox'):
125 if getattr(args, param):
126 params[param] = getattr(args, param)
128 params['accept-language'] = args.lang
129 if args.polygon_output:
130 params['polygon_' + args.polygon_output] = '1'
131 if args.polygon_threshold:
132 params['polygon_threshold'] = args.polygon_threshold
134 params['bounded'] = '1'
136 params['dedupe'] = '0'
138 return _run_api('search', args, params)
142 Execute API reverse query.
144 This command works exactly the same as if calling the /reverse endpoint on
145 the web API. See the online documentation for more details on the
147 https://nominatim.org/release-docs/latest/api/Reverse/
150 def add_args(self, parser: argparse.ArgumentParser) -> None:
151 group = parser.add_argument_group('Query arguments')
152 group.add_argument('--lat', type=float, required=True,
153 help='Latitude of coordinate to look up (in WGS84)')
154 group.add_argument('--lon', type=float, required=True,
155 help='Longitude of coordinate to look up (in WGS84)')
156 group.add_argument('--zoom', type=int,
157 help='Level of detail required for the address')
159 _add_api_output_arguments(parser)
162 def run(self, args: NominatimArgs) -> int:
163 params = dict(lat=args.lat, lon=args.lon, format=args.format)
164 if args.zoom is not None:
165 params['zoom'] = args.zoom
167 for param, _ in EXTRADATA_PARAMS:
168 if getattr(args, param):
171 params['accept-language'] = args.lang
172 if args.polygon_output:
173 params['polygon_' + args.polygon_output] = '1'
174 if args.polygon_threshold:
175 params['polygon_threshold'] = args.polygon_threshold
177 return _run_api('reverse', args, params)
182 Execute API lookup query.
184 This command works exactly the same as if calling the /lookup endpoint on
185 the web API. See the online documentation for more details on the
187 https://nominatim.org/release-docs/latest/api/Lookup/
190 def add_args(self, parser: argparse.ArgumentParser) -> None:
191 group = parser.add_argument_group('Query arguments')
192 group.add_argument('--id', metavar='OSMID',
193 action='append', required=True, dest='ids',
194 help='OSM id to lookup in format <NRW><id> (may be repeated)')
196 _add_api_output_arguments(parser)
199 def run(self, args: NominatimArgs) -> int:
200 params: Dict[str, object] = dict(osm_ids=','.join(args.ids), format=args.format)
202 for param, _ in EXTRADATA_PARAMS:
203 if getattr(args, param):
206 params['accept-language'] = args.lang
207 if args.polygon_output:
208 params['polygon_' + args.polygon_output] = '1'
209 if args.polygon_threshold:
210 params['polygon_threshold'] = args.polygon_threshold
212 return _run_api('lookup', args, params)
217 Execute API details query.
219 This command works exactly the same as if calling the /details endpoint on
220 the web API. See the online documentation for more details on the
222 https://nominatim.org/release-docs/latest/api/Details/
225 def add_args(self, parser: argparse.ArgumentParser) -> None:
226 group = parser.add_argument_group('Query arguments')
227 objs = group.add_mutually_exclusive_group(required=True)
228 objs.add_argument('--node', '-n', type=int,
229 help="Look up the OSM node with the given ID.")
230 objs.add_argument('--way', '-w', type=int,
231 help="Look up the OSM way with the given ID.")
232 objs.add_argument('--relation', '-r', type=int,
233 help="Look up the OSM relation with the given ID.")
234 objs.add_argument('--place_id', '-p', type=int,
235 help='Database internal identifier of the OSM object to look up')
236 group.add_argument('--class', dest='object_class',
237 help=("Class type to disambiguated multiple entries "
238 "of the same object."))
240 group = parser.add_argument_group('Output arguments')
241 for name, desc in DETAILS_SWITCHES:
242 group.add_argument('--' + name, action='store_true', help=desc)
243 group.add_argument('--lang', '--accept-language', metavar='LANGS',
244 help='Preferred language order for presenting search results')
247 def run(self, args: NominatimArgs) -> int:
249 params = dict(osmtype='N', osmid=args.node)
251 params = dict(osmtype='W', osmid=args.node)
253 params = dict(osmtype='R', osmid=args.node)
255 params = dict(place_id=args.place_id)
256 if args.object_class:
257 params['class'] = args.object_class
258 for name, _ in DETAILS_SWITCHES:
259 params[name] = '1' if getattr(args, name) else '0'
261 params['accept-language'] = args.lang
263 return _run_api('details', args, params)
268 Execute API status query.
270 This command works exactly the same as if calling the /status endpoint on
271 the web API. See the online documentation for more details on the
273 https://nominatim.org/release-docs/latest/api/Status/
276 def add_args(self, parser: argparse.ArgumentParser) -> None:
277 group = parser.add_argument_group('API parameters')
278 group.add_argument('--format', default='text', choices=['text', 'json'],
279 help='Format of result')
282 def run(self, args: NominatimArgs) -> int:
283 return _run_api('status', args, dict(format=args.format))