]> git.openstreetmap.org Git - nominatim.git/blob - nominatim/clicmd/api.py
Enhanced and refactored 'collect_os_info.py'
[nominatim.git] / nominatim / clicmd / api.py
1 # SPDX-License-Identifier: GPL-2.0-only
2 #
3 # This file is part of Nominatim. (https://nominatim.org)
4 #
5 # Copyright (C) 2022 by the Nominatim developer community.
6 # For a full list of authors see the git log.
7 """
8 Subcommand definitions for API calls from the command line.
9 """
10 from typing import Mapping, Dict
11 import argparse
12 import logging
13
14 from nominatim.tools.exec_utils import run_api_script
15 from nominatim.errors import UsageError
16 from nominatim.clicmd.args import NominatimArgs
17
18 # Do not repeat documentation of subcommand classes.
19 # pylint: disable=C0111
20
21 LOG = logging.getLogger()
22
23 STRUCTURED_QUERY = (
24     ('street', 'housenumber and street'),
25     ('city', 'city, town or village'),
26     ('county', 'county'),
27     ('state', 'state'),
28     ('country', 'country'),
29     ('postalcode', 'postcode')
30 )
31
32 EXTRADATA_PARAMS = (
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')
37 )
38
39 DETAILS_SWITCHES = (
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')
46 )
47
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)
55
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."))
64
65
66 def _run_api(endpoint: str, args: NominatimArgs, params: Mapping[str, object]) -> int:
67     script_file = args.project_dir / 'website' / (endpoint + '.php')
68
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.")
74
75     return run_api_script(endpoint, args.project_dir,
76                           phpcgi_bin=args.phpcgi_path, params=params)
77
78 class APISearch:
79     """\
80     Execute a search query.
81
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
84     various parameters:
85     https://nominatim.org/release-docs/latest/api/Search/
86     """
87
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)
94
95         _add_api_output_arguments(parser)
96
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')
108
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')
112
113
114     def run(self, args: NominatimArgs) -> int:
115         params: Dict[str, object]
116         if args.query:
117             params = dict(q=args.query)
118         else:
119             params = {k: getattr(args, k) for k, _ in STRUCTURED_QUERY if getattr(args, k)}
120
121         for param, _ in EXTRADATA_PARAMS:
122             if getattr(args, param):
123                 params[param] = '1'
124         for param in ('format', 'countrycodes', 'exclude_place_ids', 'limit', 'viewbox'):
125             if getattr(args, param):
126                 params[param] = getattr(args, param)
127         if args.lang:
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
133         if args.bounded:
134             params['bounded'] = '1'
135         if not args.dedupe:
136             params['dedupe'] = '0'
137
138         return _run_api('search', args, params)
139
140 class APIReverse:
141     """\
142     Execute API reverse query.
143
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
146     various parameters:
147     https://nominatim.org/release-docs/latest/api/Reverse/
148     """
149
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')
158
159         _add_api_output_arguments(parser)
160
161
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
166
167         for param, _ in EXTRADATA_PARAMS:
168             if getattr(args, param):
169                 params[param] = '1'
170         if args.lang:
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
176
177         return _run_api('reverse', args, params)
178
179
180 class APILookup:
181     """\
182     Execute API lookup query.
183
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
186     various parameters:
187     https://nominatim.org/release-docs/latest/api/Lookup/
188     """
189
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)')
195
196         _add_api_output_arguments(parser)
197
198
199     def run(self, args: NominatimArgs) -> int:
200         params: Dict[str, object] = dict(osm_ids=','.join(args.ids), format=args.format)
201
202         for param, _ in EXTRADATA_PARAMS:
203             if getattr(args, param):
204                 params[param] = '1'
205         if args.lang:
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
211
212         return _run_api('lookup', args, params)
213
214
215 class APIDetails:
216     """\
217     Execute API details query.
218
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
221     various parameters:
222     https://nominatim.org/release-docs/latest/api/Details/
223     """
224
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."))
239
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')
245
246
247     def run(self, args: NominatimArgs) -> int:
248         if args.node:
249             params = dict(osmtype='N', osmid=args.node)
250         elif args.way:
251             params = dict(osmtype='W', osmid=args.node)
252         elif args.relation:
253             params = dict(osmtype='R', osmid=args.node)
254         else:
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'
260         if args.lang:
261             params['accept-language'] = args.lang
262
263         return _run_api('details', args, params)
264
265
266 class APIStatus:
267     """\
268     Execute API status query.
269
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
272     various parameters:
273     https://nominatim.org/release-docs/latest/api/Status/
274     """
275
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')
280
281
282     def run(self, args: NominatimArgs) -> int:
283         return _run_api('status', args, dict(format=args.format))