]> git.openstreetmap.org Git - nominatim.git/blob - nominatim/clicmd/api.py
better error reporting when API script does not exist
[nominatim.git] / nominatim / clicmd / api.py
1 """
2 Subcommand definitions for API calls from the command line.
3 """
4 import logging
5
6 from nominatim.tools.exec_utils import run_api_script
7 from nominatim.errors import UsageError
8
9 # Do not repeat documentation of subcommand classes.
10 # pylint: disable=C0111
11
12 LOG = logging.getLogger()
13
14 STRUCTURED_QUERY = (
15     ('street', 'housenumber and street'),
16     ('city', 'city, town or village'),
17     ('county', 'county'),
18     ('state', 'state'),
19     ('country', 'country'),
20     ('postalcode', 'postcode')
21 )
22
23 EXTRADATA_PARAMS = (
24     ('addressdetails', 'Include a breakdown of the address into elements'),
25     ('extratags', ("Include additional information if available "
26                    "(e.g. wikipedia link, opening hours)")),
27     ('namedetails', 'Include a list of alternative names')
28 )
29
30 DETAILS_SWITCHES = (
31     ('addressdetails', 'Include a breakdown of the address into elements'),
32     ('keywords', 'Include a list of name keywords and address keywords'),
33     ('linkedplaces', 'Include a details of places that are linked with this one'),
34     ('hierarchy', 'Include details of places lower in the address hierarchy'),
35     ('group_hierarchy', 'Group the places by type'),
36     ('polygon_geojson', 'Include geometry of result')
37 )
38
39 def _add_api_output_arguments(parser):
40     group = parser.add_argument_group('Output arguments')
41     group.add_argument('--format', default='jsonv2',
42                        choices=['xml', 'json', 'jsonv2', 'geojson', 'geocodejson'],
43                        help='Format of result')
44     for name, desc in EXTRADATA_PARAMS:
45         group.add_argument('--' + name, action='store_true', help=desc)
46
47     group.add_argument('--lang', '--accept-language', metavar='LANGS',
48                        help='Preferred language order for presenting search results')
49     group.add_argument('--polygon-output',
50                        choices=['geojson', 'kml', 'svg', 'text'],
51                        help='Output geometry of results as a GeoJSON, KML, SVG or WKT')
52     group.add_argument('--polygon-threshold', type=float, metavar='TOLERANCE',
53                        help=("Simplify output geometry."
54                              "Parameter is difference tolerance in degrees."))
55
56
57 def _run_api(endpoint, args, params):
58     script_file = args.project_dir / 'website' / (endpoint + '.php')
59
60     if not script_file.exists():
61         LOG.error("Cannot find API script file.\n\n"
62                   "Make sure to run 'nominatim' from the project directory \n"
63                   "or use the option --project-dir.")
64         raise UsageError("API script not found.")
65
66     return run_api_script(endpoint, args.project_dir,
67                           phpcgi_bin=args.phpcgi_path, params=params)
68
69 class APISearch:
70     """\
71     Execute a search query.
72
73     This command works exactly the same as if calling the /search endpoint on
74     the web API. See the online documentation for more details on the
75     various parameters:
76     https://nominatim.org/release-docs/latest/api/Search/
77     """
78
79     @staticmethod
80     def add_args(parser):
81         group = parser.add_argument_group('Query arguments')
82         group.add_argument('--query',
83                            help='Free-form query string')
84         for name, desc in STRUCTURED_QUERY:
85             group.add_argument('--' + name, help='Structured query: ' + desc)
86
87         _add_api_output_arguments(parser)
88
89         group = parser.add_argument_group('Result limitation')
90         group.add_argument('--countrycodes', metavar='CC,..',
91                            help='Limit search results to one or more countries')
92         group.add_argument('--exclude_place_ids', metavar='ID,..',
93                            help='List of search object to be excluded')
94         group.add_argument('--limit', type=int,
95                            help='Limit the number of returned results')
96         group.add_argument('--viewbox', metavar='X1,Y1,X2,Y2',
97                            help='Preferred area to find search results')
98         group.add_argument('--bounded', action='store_true',
99                            help='Strictly restrict results to viewbox area')
100
101         group = parser.add_argument_group('Other arguments')
102         group.add_argument('--no-dedupe', action='store_false', dest='dedupe',
103                            help='Do not remove duplicates from the result list')
104
105
106     @staticmethod
107     def run(args):
108         if args.query:
109             params = dict(q=args.query)
110         else:
111             params = {k: getattr(args, k) for k, _ in STRUCTURED_QUERY if getattr(args, k)}
112
113         for param, _ in EXTRADATA_PARAMS:
114             if getattr(args, param):
115                 params[param] = '1'
116         for param in ('format', 'countrycodes', 'exclude_place_ids', 'limit', 'viewbox'):
117             if getattr(args, param):
118                 params[param] = getattr(args, param)
119         if args.lang:
120             params['accept-language'] = args.lang
121         if args.polygon_output:
122             params['polygon_' + args.polygon_output] = '1'
123         if args.polygon_threshold:
124             params['polygon_threshold'] = args.polygon_threshold
125         if args.bounded:
126             params['bounded'] = '1'
127         if not args.dedupe:
128             params['dedupe'] = '0'
129
130         return _run_api('search', args, params)
131
132 class APIReverse:
133     """\
134     Execute API reverse query.
135
136     This command works exactly the same as if calling the /reverse endpoint on
137     the web API. See the online documentation for more details on the
138     various parameters:
139     https://nominatim.org/release-docs/latest/api/Reverse/
140     """
141
142     @staticmethod
143     def add_args(parser):
144         group = parser.add_argument_group('Query arguments')
145         group.add_argument('--lat', type=float, required=True,
146                            help='Latitude of coordinate to look up (in WGS84)')
147         group.add_argument('--lon', type=float, required=True,
148                            help='Longitude of coordinate to look up (in WGS84)')
149         group.add_argument('--zoom', type=int,
150                            help='Level of detail required for the address')
151
152         _add_api_output_arguments(parser)
153
154
155     @staticmethod
156     def run(args):
157         params = dict(lat=args.lat, lon=args.lon)
158         if args.zoom is not None:
159             params['zoom'] = args.zoom
160
161         for param, _ in EXTRADATA_PARAMS:
162             if getattr(args, param):
163                 params[param] = '1'
164         if args.format:
165             params['format'] = args.format
166         if args.lang:
167             params['accept-language'] = args.lang
168         if args.polygon_output:
169             params['polygon_' + args.polygon_output] = '1'
170         if args.polygon_threshold:
171             params['polygon_threshold'] = args.polygon_threshold
172
173         return _run_api('reverse', args, params)
174
175
176 class APILookup:
177     """\
178     Execute API lookup query.
179
180     This command works exactly the same as if calling the /lookup endpoint on
181     the web API. See the online documentation for more details on the
182     various parameters:
183     https://nominatim.org/release-docs/latest/api/Lookup/
184     """
185
186     @staticmethod
187     def add_args(parser):
188         group = parser.add_argument_group('Query arguments')
189         group.add_argument('--id', metavar='OSMID',
190                            action='append', required=True, dest='ids',
191                            help='OSM id to lookup in format <NRW><id> (may be repeated)')
192
193         _add_api_output_arguments(parser)
194
195
196     @staticmethod
197     def run(args):
198         params = dict(osm_ids=','.join(args.ids))
199
200         for param, _ in EXTRADATA_PARAMS:
201             if getattr(args, param):
202                 params[param] = '1'
203         if args.format:
204             params['format'] = args.format
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     @staticmethod
226     def add_args(parser):
227         group = parser.add_argument_group('Query arguments')
228         objs = group.add_mutually_exclusive_group(required=True)
229         objs.add_argument('--node', '-n', type=int,
230                           help="Look up the OSM node with the given ID.")
231         objs.add_argument('--way', '-w', type=int,
232                           help="Look up the OSM way with the given ID.")
233         objs.add_argument('--relation', '-r', type=int,
234                           help="Look up the OSM relation with the given ID.")
235         objs.add_argument('--place_id', '-p', type=int,
236                           help='Database internal identifier of the OSM object to look up')
237         group.add_argument('--class', dest='object_class',
238                            help=("Class type to disambiguated multiple entries "
239                                  "of the same object."))
240
241         group = parser.add_argument_group('Output arguments')
242         for name, desc in DETAILS_SWITCHES:
243             group.add_argument('--' + name, action='store_true', help=desc)
244         group.add_argument('--lang', '--accept-language', metavar='LANGS',
245                            help='Preferred language order for presenting search results')
246
247     @staticmethod
248     def run(args):
249         if args.node:
250             params = dict(osmtype='N', osmid=args.node)
251         elif args.way:
252             params = dict(osmtype='W', osmid=args.node)
253         elif args.relation:
254             params = dict(osmtype='R', osmid=args.node)
255         else:
256             params = dict(place_id=args.place_id)
257         if args.object_class:
258             params['class'] = args.object_class
259         for name, _ in DETAILS_SWITCHES:
260             params[name] = '1' if getattr(args, name) else '0'
261
262         return _run_api('details', args, params)
263
264
265 class APIStatus:
266     """\
267     Execute API status query.
268
269     This command works exactly the same as if calling the /status endpoint on
270     the web API. See the online documentation for more details on the
271     various parameters:
272     https://nominatim.org/release-docs/latest/api/Status/
273     """
274
275     @staticmethod
276     def add_args(parser):
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     @staticmethod
282     def run(args):
283         return _run_api('status', args, dict(format=args.format))