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