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 Server implementation using the sanic webserver framework.
10 from typing import Any, Optional, Mapping
11 from pathlib import Path
15 from nominatim.api import NominatimAPIAsync, StatusResult
16 import nominatim.api.v1 as api_impl
18 api = sanic.Blueprint('NominatimAPI')
21 'text': 'text/plain; charset=utf-8',
22 'xml': 'text/xml; charset=utf-8'
25 def usage_error(msg: str) -> sanic.HTTPResponse:
26 """ Format the response for an error with the query parameters.
28 return sanic.response.text(msg, status=400)
31 def api_response(request: sanic.Request, result: Any) -> sanic.HTTPResponse:
32 """ Render a response from the query results using the configured
35 body = api_impl.format_result(result, request.ctx.format)
36 return sanic.response.text(body,
37 content_type=CONTENT_TYPE.get(request.ctx.format,
41 @api.on_request # type: ignore[misc]
42 async def extract_format(request: sanic.Request) -> Optional[sanic.HTTPResponse]:
43 """ Get and check the 'format' parameter and prepare the formatter.
44 `ctx.result_type` describes the expected return type and
45 `ctx.default_format` the format value to assume when no parameter
48 assert request.route is not None
50 request.ctx.format = request.args.get('format', request.route.ctx.default_format)
51 if not api_impl.supports_format(request.route.ctx.result_type, request.ctx.format):
52 return usage_error("Parameter 'format' must be one of: " +
53 ', '.join(api_impl.list_formats(request.route.ctx.result_type)))
58 @api.get('/status', ctx_result_type=StatusResult, ctx_default_format='text')
59 async def status(request: sanic.Request) -> sanic.HTTPResponse:
60 """ Implementation of status endpoint.
62 result = await request.app.ctx.api.status()
63 response = api_response(request, result)
65 if request.ctx.format == 'text' and result.status:
71 def get_application(project_dir: Path,
72 environ: Optional[Mapping[str, str]] = None) -> sanic.Sanic:
73 """ Create a Nominatim sanic ASGI application.
75 app = sanic.Sanic("NominatimInstance")
77 app.ctx.api = NominatimAPIAsync(project_dir, environ)