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
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, StatusResult
18 import nominatim.api.v1 as api_output
20 # Do not repeat documentation of subcommand classes.
21 # pylint: disable=C0111
23 LOG = logging.getLogger()
26 ('street', 'housenumber and street'),
27 ('city', 'city, town or village'),
30 ('country', 'country'),
31 ('postalcode', 'postcode')
35 ('addressdetails', 'Include a breakdown of the address into elements'),
36 ('extratags', ("Include additional information if available "
37 "(e.g. wikipedia link, opening hours)")),
38 ('namedetails', 'Include a list of alternative names')
42 ('addressdetails', 'Include a breakdown of the address into elements'),
43 ('keywords', 'Include a list of name keywords and address keywords'),
44 ('linkedplaces', 'Include a details of places that are linked with this one'),
45 ('hierarchy', 'Include details of places lower in the address hierarchy'),
46 ('group_hierarchy', 'Group the places by type'),
47 ('polygon_geojson', 'Include geometry of result')
50 def _add_api_output_arguments(parser: argparse.ArgumentParser) -> None:
51 group = parser.add_argument_group('Output arguments')
52 group.add_argument('--format', default='jsonv2',
53 choices=['xml', 'json', 'jsonv2', 'geojson', 'geocodejson'],
54 help='Format of result')
55 for name, desc in EXTRADATA_PARAMS:
56 group.add_argument('--' + name, action='store_true', help=desc)
58 group.add_argument('--lang', '--accept-language', metavar='LANGS',
59 help='Preferred language order for presenting search results')
60 group.add_argument('--polygon-output',
61 choices=['geojson', 'kml', 'svg', 'text'],
62 help='Output geometry of results as a GeoJSON, KML, SVG or WKT')
63 group.add_argument('--polygon-threshold', type=float, metavar='TOLERANCE',
64 help=("Simplify output geometry."
65 "Parameter is difference tolerance in degrees."))
68 def _run_api(endpoint: str, args: NominatimArgs, params: Mapping[str, object]) -> int:
69 script_file = args.project_dir / 'website' / (endpoint + '.php')
71 if not script_file.exists():
72 LOG.error("Cannot find API script file.\n\n"
73 "Make sure to run 'nominatim' from the project directory \n"
74 "or use the option --project-dir.")
75 raise UsageError("API script not found.")
77 return run_api_script(endpoint, args.project_dir,
78 phpcgi_bin=args.phpcgi_path, params=params)
82 Execute a search query.
84 This command works exactly the same as if calling the /search endpoint on
85 the web API. See the online documentation for more details on the
87 https://nominatim.org/release-docs/latest/api/Search/
90 def add_args(self, parser: argparse.ArgumentParser) -> None:
91 group = parser.add_argument_group('Query arguments')
92 group.add_argument('--query',
93 help='Free-form query string')
94 for name, desc in STRUCTURED_QUERY:
95 group.add_argument('--' + name, help='Structured query: ' + desc)
97 _add_api_output_arguments(parser)
99 group = parser.add_argument_group('Result limitation')
100 group.add_argument('--countrycodes', metavar='CC,..',
101 help='Limit search results to one or more countries')
102 group.add_argument('--exclude_place_ids', metavar='ID,..',
103 help='List of search object to be excluded')
104 group.add_argument('--limit', type=int,
105 help='Limit the number of returned results')
106 group.add_argument('--viewbox', metavar='X1,Y1,X2,Y2',
107 help='Preferred area to find search results')
108 group.add_argument('--bounded', action='store_true',
109 help='Strictly restrict results to viewbox area')
111 group = parser.add_argument_group('Other arguments')
112 group.add_argument('--no-dedupe', action='store_false', dest='dedupe',
113 help='Do not remove duplicates from the result list')
116 def run(self, args: NominatimArgs) -> int:
117 params: Dict[str, object]
119 params = dict(q=args.query)
121 params = {k: getattr(args, k) for k, _ in STRUCTURED_QUERY if getattr(args, k)}
123 for param, _ in EXTRADATA_PARAMS:
124 if getattr(args, param):
126 for param in ('format', 'countrycodes', 'exclude_place_ids', 'limit', 'viewbox'):
127 if getattr(args, param):
128 params[param] = getattr(args, param)
130 params['accept-language'] = args.lang
131 if args.polygon_output:
132 params['polygon_' + args.polygon_output] = '1'
133 if args.polygon_threshold:
134 params['polygon_threshold'] = args.polygon_threshold
136 params['bounded'] = '1'
138 params['dedupe'] = '0'
140 return _run_api('search', args, params)
144 Execute API reverse query.
146 This command works exactly the same as if calling the /reverse endpoint on
147 the web API. See the online documentation for more details on the
149 https://nominatim.org/release-docs/latest/api/Reverse/
152 def add_args(self, parser: argparse.ArgumentParser) -> None:
153 group = parser.add_argument_group('Query arguments')
154 group.add_argument('--lat', type=float, required=True,
155 help='Latitude of coordinate to look up (in WGS84)')
156 group.add_argument('--lon', type=float, required=True,
157 help='Longitude of coordinate to look up (in WGS84)')
158 group.add_argument('--zoom', type=int,
159 help='Level of detail required for the address')
161 _add_api_output_arguments(parser)
164 def run(self, args: NominatimArgs) -> int:
165 params = dict(lat=args.lat, lon=args.lon, format=args.format)
166 if args.zoom is not None:
167 params['zoom'] = args.zoom
169 for param, _ in EXTRADATA_PARAMS:
170 if getattr(args, param):
173 params['accept-language'] = args.lang
174 if args.polygon_output:
175 params['polygon_' + args.polygon_output] = '1'
176 if args.polygon_threshold:
177 params['polygon_threshold'] = args.polygon_threshold
179 return _run_api('reverse', args, params)
184 Execute API lookup query.
186 This command works exactly the same as if calling the /lookup endpoint on
187 the web API. See the online documentation for more details on the
189 https://nominatim.org/release-docs/latest/api/Lookup/
192 def add_args(self, parser: argparse.ArgumentParser) -> None:
193 group = parser.add_argument_group('Query arguments')
194 group.add_argument('--id', metavar='OSMID',
195 action='append', required=True, dest='ids',
196 help='OSM id to lookup in format <NRW><id> (may be repeated)')
198 _add_api_output_arguments(parser)
201 def run(self, args: NominatimArgs) -> int:
202 params: Dict[str, object] = dict(osm_ids=','.join(args.ids), format=args.format)
204 for param, _ in EXTRADATA_PARAMS:
205 if getattr(args, param):
208 params['accept-language'] = args.lang
209 if args.polygon_output:
210 params['polygon_' + args.polygon_output] = '1'
211 if args.polygon_threshold:
212 params['polygon_threshold'] = args.polygon_threshold
214 return _run_api('lookup', args, params)
219 Execute API details query.
221 This command works exactly the same as if calling the /details endpoint on
222 the web API. See the online documentation for more details on the
224 https://nominatim.org/release-docs/latest/api/Details/
227 def add_args(self, parser: argparse.ArgumentParser) -> None:
228 group = parser.add_argument_group('Query arguments')
229 objs = group.add_mutually_exclusive_group(required=True)
230 objs.add_argument('--node', '-n', type=int,
231 help="Look up the OSM node with the given ID.")
232 objs.add_argument('--way', '-w', type=int,
233 help="Look up the OSM way with the given ID.")
234 objs.add_argument('--relation', '-r', type=int,
235 help="Look up the OSM relation with the given ID.")
236 objs.add_argument('--place_id', '-p', type=int,
237 help='Database internal identifier of the OSM object to look up')
238 group.add_argument('--class', dest='object_class',
239 help=("Class type to disambiguated multiple entries "
240 "of the same object."))
242 group = parser.add_argument_group('Output arguments')
243 for name, desc in DETAILS_SWITCHES:
244 group.add_argument('--' + name, action='store_true', help=desc)
245 group.add_argument('--lang', '--accept-language', metavar='LANGS',
246 help='Preferred language order for presenting search results')
249 def run(self, args: NominatimArgs) -> int:
251 params = dict(osmtype='N', osmid=args.node)
253 params = dict(osmtype='W', osmid=args.way)
255 params = dict(osmtype='R', osmid=args.relation)
257 params = dict(place_id=args.place_id)
258 if args.object_class:
259 params['class'] = args.object_class
260 for name, _ in DETAILS_SWITCHES:
261 params[name] = '1' if getattr(args, name) else '0'
263 params['accept-language'] = args.lang
265 return _run_api('details', args, params)
270 Execute API status query.
272 This command works exactly the same as if calling the /status endpoint on
273 the web API. See the online documentation for more details on the
275 https://nominatim.org/release-docs/latest/api/Status/
278 def add_args(self, parser: argparse.ArgumentParser) -> None:
279 formats = api_output.list_formats(StatusResult)
280 group = parser.add_argument_group('API parameters')
281 group.add_argument('--format', default=formats[0], choices=formats,
282 help='Format of result')
285 def run(self, args: NominatimArgs) -> int:
286 status = NominatimAPI(args.project_dir).status()
287 print(api_output.format_result(status, args.format))