|
| 1 | +"""Declaration of FastAPI application.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import re |
| 6 | + |
| 7 | +import pydantic as pdt |
| 8 | +from aiida import __version__ as aiida_version |
| 9 | +from fastapi import APIRouter, Request |
| 10 | +from fastapi.responses import HTMLResponse |
| 11 | +from fastapi.routing import APIRoute |
| 12 | +from starlette.routing import Route |
| 13 | + |
| 14 | +from aiida_restapi.config import API_CONFIG |
| 15 | + |
| 16 | +read_router = APIRouter() |
| 17 | + |
| 18 | + |
| 19 | +class ServerInfo(pdt.BaseModel): |
| 20 | + """API version information.""" |
| 21 | + |
| 22 | + API_major_version: str = pdt.Field(description='Major version of the API') |
| 23 | + API_minor_version: str = pdt.Field(description='Minor version of the API') |
| 24 | + API_revision_version: str = pdt.Field(description='Revision version of the API') |
| 25 | + API_prefix: str = pdt.Field(description='Prefix for all API endpoints') |
| 26 | + AiiDA_version: str = pdt.Field(description='Version of the AiiDA installation') |
| 27 | + |
| 28 | + |
| 29 | +@read_router.get('/server/info', response_model=ServerInfo) |
| 30 | +async def get_server_info() -> ServerInfo: |
| 31 | + """Get the API version information.""" |
| 32 | + api_version = API_CONFIG['VERSION'].split('.') |
| 33 | + return ServerInfo( |
| 34 | + API_major_version=api_version[0], |
| 35 | + API_minor_version=api_version[1], |
| 36 | + API_revision_version=api_version[2], |
| 37 | + API_prefix=API_CONFIG['PREFIX'], |
| 38 | + AiiDA_version=aiida_version, |
| 39 | + ) |
| 40 | + |
| 41 | + |
| 42 | +class ServerEndpoint(pdt.BaseModel): |
| 43 | + """API endpoint.""" |
| 44 | + |
| 45 | + path: str = pdt.Field(description='Path of the endpoint') |
| 46 | + group: str | None = pdt.Field(description='Group of the endpoint') |
| 47 | + methods: set[str] = pdt.Field(description='HTTP methods supported by the endpoint') |
| 48 | + description: str = pdt.Field('-', description='Description of the endpoint') |
| 49 | + |
| 50 | + |
| 51 | +@read_router.get( |
| 52 | + '/server/endpoints', |
| 53 | + name='endpoints', |
| 54 | + response_model=dict[str, list[ServerEndpoint]], |
| 55 | +) |
| 56 | +async def get_server_endpoints(request: Request) -> dict[str, list[ServerEndpoint]]: |
| 57 | + """Get a JSON-serializable dictionary of all registered API routes. |
| 58 | +
|
| 59 | + :param request: The FastAPI request object. |
| 60 | + :return: A JSON-serializable dictionary of all registered API routes. |
| 61 | + """ |
| 62 | + endpoints: list[ServerEndpoint] = [] |
| 63 | + |
| 64 | + for route in request.app.routes: |
| 65 | + if route.path == '/': |
| 66 | + continue |
| 67 | + |
| 68 | + group, methods, description = _get_route_parts(route) |
| 69 | + base_url = str(request.base_url).rstrip('/') |
| 70 | + |
| 71 | + endpoint = { |
| 72 | + 'path': base_url + route.path, |
| 73 | + 'group': group, |
| 74 | + 'methods': methods, |
| 75 | + 'description': description, |
| 76 | + } |
| 77 | + |
| 78 | + endpoints.append(ServerEndpoint(**endpoint)) |
| 79 | + |
| 80 | + return {'endpoints': endpoints} |
| 81 | + |
| 82 | + |
| 83 | +@read_router.get( |
| 84 | + '/server/endpoints/table', |
| 85 | + response_class=HTMLResponse, |
| 86 | +) |
| 87 | +async def get_server_endpoints_table(request: Request) -> HTMLResponse: |
| 88 | + """Get an HTML table of all registered API routes. |
| 89 | +
|
| 90 | + :param request: The FastAPI request object. |
| 91 | + :return: An HTML table of all registered API routes. |
| 92 | + """ |
| 93 | + routes = request.app.routes |
| 94 | + base_url = str(request.base_url).rstrip('/') |
| 95 | + |
| 96 | + rows = [] |
| 97 | + |
| 98 | + for route in routes: |
| 99 | + if route.path == '/': |
| 100 | + continue |
| 101 | + |
| 102 | + path = base_url + route.path |
| 103 | + group, methods, description = _get_route_parts(route) |
| 104 | + |
| 105 | + disable_url = ( |
| 106 | + ( |
| 107 | + isinstance(route, APIRoute) |
| 108 | + and any( |
| 109 | + param |
| 110 | + for param in route.dependant.path_params |
| 111 | + + route.dependant.query_params |
| 112 | + + route.dependant.body_params |
| 113 | + if param.required |
| 114 | + ) |
| 115 | + ) |
| 116 | + or (route.methods and 'POST' in route.methods) |
| 117 | + or 'auth' in path |
| 118 | + ) |
| 119 | + |
| 120 | + path_row = path if disable_url else f'<a href="{path}">{path}</a>' |
| 121 | + |
| 122 | + rows.append(f""" |
| 123 | + <tr> |
| 124 | + <td>{path_row}</td> |
| 125 | + <td>{group or '-'}</td> |
| 126 | + <td>{', '.join(methods)}</td> |
| 127 | + <td>{description or '-'}</td> |
| 128 | + </tr> |
| 129 | + """) |
| 130 | + |
| 131 | + return HTMLResponse( |
| 132 | + content=f""" |
| 133 | + <html> |
| 134 | + <head> |
| 135 | + <title>AiiDA REST API Endpoints</title> |
| 136 | + <style> |
| 137 | + body {{ |
| 138 | + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; |
| 139 | + padding: 1em; |
| 140 | + color: #222; |
| 141 | + }} |
| 142 | + h1 {{ |
| 143 | + margin-bottom: 0.5em; |
| 144 | + }} |
| 145 | + table {{ |
| 146 | + border-collapse: collapse; |
| 147 | + width: 100%; |
| 148 | + }} |
| 149 | + th, td {{ |
| 150 | + border: 1px solid #ddd; |
| 151 | + padding: 0.5em 0.75em; |
| 152 | + text-align: left; |
| 153 | + }} |
| 154 | + th {{ |
| 155 | + background-color: #f4f4f4; |
| 156 | + }} |
| 157 | + tr:nth-child(even) {{ |
| 158 | + background-color: #fafafa; |
| 159 | + }} |
| 160 | + tr:hover {{ |
| 161 | + background-color: #f1f1f1; |
| 162 | + }} |
| 163 | + a {{ |
| 164 | + text-decoration: none; |
| 165 | + color: #0066cc; |
| 166 | + }} |
| 167 | + a:hover {{ |
| 168 | + text-decoration: underline; |
| 169 | + }} |
| 170 | + </style> |
| 171 | + </head> |
| 172 | + <body> |
| 173 | + <h1>AiiDA REST API Endpoints</h1> |
| 174 | + <table> |
| 175 | + <thead> |
| 176 | + <tr> |
| 177 | + <th>URL</th> |
| 178 | + <th>Group</th> |
| 179 | + <th>Methods</th> |
| 180 | + <th>Description</th> |
| 181 | + </tr> |
| 182 | + </thead> |
| 183 | + <tbody> |
| 184 | + {''.join(rows)} |
| 185 | + </tbody> |
| 186 | + </table> |
| 187 | + </body> |
| 188 | + </html> |
| 189 | + """ |
| 190 | + ) |
| 191 | + |
| 192 | + |
| 193 | +def _get_route_parts(route: Route) -> tuple[str | None, set[str], str]: |
| 194 | + """Return the parts of a route: path, group, methods, description. |
| 195 | +
|
| 196 | + :param route: A FastAPI/Starlette Route object. |
| 197 | + :return: A tuple containing the group, methods, and description of the route. |
| 198 | + """ |
| 199 | + prefix = re.escape(API_CONFIG['PREFIX']) |
| 200 | + match = re.match(rf'^{prefix}/([^/]+)/?.*', route.path) |
| 201 | + group = match.group(1) if match else None |
| 202 | + methods = (route.methods or set()) - {'HEAD', 'OPTIONS'} |
| 203 | + description = (route.endpoint.__doc__ or '').split('\n')[0].strip() |
| 204 | + return group, methods, description |
0 commit comments