-
Notifications
You must be signed in to change notification settings - Fork 466
Expand file tree
/
Copy pathOpenAPI31Exporter.scala
More file actions
410 lines (350 loc) · 14.3 KB
/
OpenAPI31Exporter.scala
File metadata and controls
410 lines (350 loc) · 14.3 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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
#!/usr/bin/env scala
/**
* OpenAPI 3.1 Exporter for OBP API v6.0.0
*
* This script extracts API documentation from the OBP API v6.0.0 codebase
* and converts it to OpenAPI 3.1 format.
*
* Usage:
* scala OpenAPI31Exporter.scala [output_file]
*
* If no output file is specified, it writes to stdout.
*/
import scala.io.Source
import scala.util.matching.Regex
import java.io.{File, PrintWriter}
import scala.collection.mutable.ListBuffer
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
case class ApiEndpoint(
name: String,
method: String,
path: String,
summary: String,
description: String,
requestBody: Option[String],
responseBody: Option[String],
errorCodes: List[String],
tags: List[String],
roles: List[String] = List.empty
)
case class JsonSchema(
name: String,
properties: Map[String, Any],
required: List[String] = List.empty,
description: Option[String] = None
)
object OpenAPI31Exporter {
def main(args: Array[String]): Unit = {
val outputFile = if (args.length > 0) Some(args(0)) else None
val projectRoot = findProjectRoot()
println(s"Extracting API documentation from: $projectRoot")
val endpoints = extractEndpoints(projectRoot)
val schemas = extractSchemas(projectRoot)
val openApiYaml = generateOpenAPI31(endpoints, schemas)
outputFile match {
case Some(file) =>
val writer = new PrintWriter(new File(file))
try {
writer.write(openApiYaml)
println(s"OpenAPI 3.1 documentation written to: $file")
} finally {
writer.close()
}
case None =>
println(openApiYaml)
}
}
def findProjectRoot(): String = {
val currentDir = new File(".")
val candidates = List(
"./obp-api/src/main/scala/code/api/v6_0_0",
"../obp-api/src/main/scala/code/api/v6_0_0",
"./OBP-API/obp-api/src/main/scala/code/api/v6_0_0"
)
candidates.find(path => new File(path).exists()) match {
case Some(path) => new File(path).getParentFile.getParentFile.getParentFile.getParentFile.getParentFile.getAbsolutePath
case None =>
throw new RuntimeException("Could not find OBP API project root. Please run from the project directory.")
}
}
def extractEndpoints(projectRoot: String): List[ApiEndpoint] = {
val apiMethodsFile = new File(s"$projectRoot/obp-api/src/main/scala/code/api/v6_0_0/APIMethods600.scala")
val endpoints = ListBuffer[ApiEndpoint]()
if (!apiMethodsFile.exists()) {
throw new RuntimeException(s"APIMethods600.scala not found at: ${apiMethodsFile.getAbsolutePath}")
}
val content = Source.fromFile(apiMethodsFile).getLines().mkString("\n")
// Extract ResourceDoc definitions
val resourceDocPattern = """staticResourceDocs \+= ResourceDoc\(\s*([^,]+),\s*[^,]+,\s*[^,]+,\s*"([^"]+)",\s*"([^"]+)",\s*"([^"]+)",\s*s?"""([^"]*(?:"[^"]*"[^"]*)*?)""",\s*([^,]+),\s*([^,]+),\s*List\(([^)]*)\),\s*List\(([^)]*)\)(?:,\s*Some\(List\(([^)]*)\)))?\s*\)""".r
resourceDocPattern.findAllMatchIn(content).foreach { m =>
val endpointName = m.group(1).trim
val method = m.group(2).trim
val path = m.group(3).trim
val summary = m.group(4).trim
val description = cleanDescription(m.group(5))
val requestBodyRef = m.group(6).trim
val responseBodyRef = m.group(7).trim
val errorCodes = parseList(m.group(8))
val tags = parseList(m.group(9))
val roles = if (m.group(10) != null) parseList(m.group(10)) else List.empty
endpoints += ApiEndpoint(
name = endpointName,
method = method,
path = path,
summary = summary,
description = description,
requestBody = if (requestBodyRef != "EmptyBody") Some(requestBodyRef) else None,
responseBody = Some(responseBodyRef),
errorCodes = errorCodes,
tags = tags,
roles = roles
)
}
endpoints.toList
}
def extractSchemas(projectRoot: String): List[JsonSchema] = {
val jsonFactoryFile = new File(s"$projectRoot/obp-api/src/main/scala/code/api/v6_0_0/JSONFactory6.0.0.scala")
val schemas = ListBuffer[JsonSchema]()
if (!jsonFactoryFile.exists()) {
println(s"Warning: JSONFactory6.0.0.scala not found at: ${jsonFactoryFile.getAbsolutePath}")
return schemas.toList
}
val content = Source.fromFile(jsonFactoryFile).getLines().mkString("\n")
// Extract case class definitions
val caseClassPattern = """case class ([A-Za-z0-9_]+)\(\s*(.*?)\s*\)""".r
caseClassPattern.findAllMatchIn(content).foreach { m =>
val className = m.group(1)
val fieldsStr = m.group(2)
val properties = parseFields(fieldsStr)
val required = properties.filter(_._2.asInstanceOf[Map[String, Any]].get("nullable").isEmpty).keys.toList
schemas += JsonSchema(
name = className,
properties = properties,
required = required,
description = Some(s"Schema for $className")
)
}
schemas.toList
}
def parseFields(fieldsStr: String): Map[String, Any] = {
val properties = scala.collection.mutable.Map[String, Any]()
if (fieldsStr.trim.nonEmpty) {
val fieldPattern = """([a-zA-Z_][a-zA-Z0-9_]*)\s*:\s*([^,]+)""".r
fieldPattern.findAllMatchIn(fieldsStr).foreach { m =>
val fieldName = m.group(1).trim
val fieldType = m.group(2).trim
val (schemaType, nullable) = mapScalaTypeToJsonSchema(fieldType)
val fieldSchema = scala.collection.mutable.Map[String, Any](
"type" -> schemaType
)
if (nullable) {
fieldSchema += "nullable" -> true
}
if (fieldType.contains("Date")) {
fieldSchema += "format" -> "date-time"
}
properties += fieldName -> fieldSchema.toMap
}
}
properties.toMap
}
def mapScalaTypeToJsonSchema(scalaType: String): (String, Boolean) = {
val cleanType = scalaType.replaceAll("Option\\[(.*)\\]", "$1").trim
val nullable = scalaType.contains("Option[")
val jsonType = cleanType match {
case t if t.startsWith("String") => "string"
case t if t.startsWith("Int") || t.startsWith("Long") => "integer"
case t if t.startsWith("Double") || t.startsWith("Float") || t.startsWith("BigDecimal") => "number"
case t if t.startsWith("Boolean") => "boolean"
case t if t.startsWith("List[") || t.startsWith("Array[") => "array"
case t if t.contains("Date") => "string"
case _ => "object"
}
(jsonType, nullable)
}
def cleanDescription(desc: String): String = {
desc.replaceAll("\\|", "")
.replaceAll("\\$\\{[^}]+\\}", "")
.replaceAll("\\s+", " ")
.trim
}
def parseList(listStr: String): List[String] = {
if (listStr.trim.isEmpty) List.empty
else listStr.split(",").map(_.trim.replaceAll("[\"$]", "")).filter(_.nonEmpty).toList
}
def generateOpenAPI31(endpoints: List[ApiEndpoint], schemas: List[JsonSchema]): String = {
val timestamp = LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
val yaml = new StringBuilder()
// OpenAPI header
yaml.append("openapi: 3.1.0\n")
yaml.append("\n")
yaml.append("info:\n")
yaml.append(" title: Open Bank Project API v6.0.0\n")
yaml.append(" version: 6.0.0\n")
yaml.append(" description: |\n")
yaml.append(" The Open Bank Project API v6.0.0 provides standardized banking APIs.\n")
yaml.append(" \n")
yaml.append(" This specification was automatically generated from the OBP API codebase.\n")
yaml.append(s" Generated on: $timestamp\n")
yaml.append(" \n")
yaml.append(" For more information, visit: https://github.com/OpenBankProject/OBP-API\n")
yaml.append(" contact:\n")
yaml.append(" name: Open Bank Project\n")
yaml.append(" url: https://www.openbankproject.com\n")
yaml.append(" email: [email protected]\n")
yaml.append(" license:\n")
yaml.append(" name: AGPL v3\n")
yaml.append(" url: https://www.gnu.org/licenses/agpl-3.0.html\n")
yaml.append("\n")
// Servers
yaml.append("servers:\n")
yaml.append(" - url: https://api.openbankproject.com\n")
yaml.append(" description: Production server\n")
yaml.append(" - url: https://apisandbox.openbankproject.com\n")
yaml.append(" description: Sandbox server\n")
yaml.append("\n")
// Security schemes
yaml.append("components:\n")
yaml.append(" securitySchemes:\n")
yaml.append(" DirectLogin:\n")
yaml.append(" type: apiKey\n")
yaml.append(" in: header\n")
yaml.append(" name: Authorization\n")
yaml.append(" description: Direct Login token authentication\n")
yaml.append(" GatewayLogin:\n")
yaml.append(" type: apiKey\n")
yaml.append(" in: header\n")
yaml.append(" name: Authorization\n")
yaml.append(" description: Gateway Login token authentication\n")
yaml.append(" OAuth2:\n")
yaml.append(" type: oauth2\n")
yaml.append(" flows:\n")
yaml.append(" authorizationCode:\n")
yaml.append(" authorizationUrl: /oauth/authorize\n")
yaml.append(" tokenUrl: /oauth/token\n")
yaml.append(" scopes: {}\n")
yaml.append("\n")
// Schemas
if (schemas.nonEmpty) {
yaml.append(" schemas:\n")
schemas.foreach { schema =>
yaml.append(s" ${schema.name}:\n")
yaml.append(" type: object\n")
if (schema.description.isDefined) {
yaml.append(s" description: ${schema.description.get}\n")
}
if (schema.required.nonEmpty) {
yaml.append(" required:\n")
schema.required.foreach { field =>
yaml.append(s" - $field\n")
}
}
if (schema.properties.nonEmpty) {
yaml.append(" properties:\n")
schema.properties.foreach { case (name, propSchema) =>
val props = propSchema.asInstanceOf[Map[String, Any]]
yaml.append(s" $name:\n")
yaml.append(s" type: ${props("type")}\n")
props.get("format").foreach { format =>
yaml.append(s" format: $format\n")
}
props.get("nullable").foreach { _ =>
yaml.append(" nullable: true\n")
}
}
}
yaml.append("\n")
}
}
// Paths
yaml.append("paths:\n")
val groupedEndpoints = endpoints.groupBy(_.path)
groupedEndpoints.toSeq.sortBy(_._1).foreach { case (path, pathEndpoints) =>
val openApiPath = convertPathToOpenAPI(path)
yaml.append(s" $openApiPath:\n")
pathEndpoints.sortBy(_.method).foreach { endpoint =>
val method = endpoint.method.toLowerCase
yaml.append(s" $method:\n")
yaml.append(s" summary: ${endpoint.summary}\n")
yaml.append(s" operationId: ${endpoint.name}\n")
if (endpoint.description.nonEmpty) {
yaml.append(" description: |\n")
endpoint.description.split("\n").foreach { line =>
yaml.append(s" $line\n")
}
}
if (endpoint.tags.nonEmpty) {
yaml.append(" tags:\n")
endpoint.tags.foreach { tag =>
yaml.append(s" - ${tag.replaceAll("apiTag", "")}\n")
}
}
// Parameters (path parameters)
val pathParams = extractPathParameters(path)
if (pathParams.nonEmpty) {
yaml.append(" parameters:\n")
pathParams.foreach { param =>
yaml.append(s" - name: $param\n")
yaml.append(" in: path\n")
yaml.append(" required: true\n")
yaml.append(" schema:\n")
yaml.append(" type: string\n")
}
}
// Request body
if (endpoint.requestBody.isDefined && method != "get" && method != "delete") {
yaml.append(" requestBody:\n")
yaml.append(" required: true\n")
yaml.append(" content:\n")
yaml.append(" application/json:\n")
yaml.append(" schema:\n")
yaml.append(s" $$ref: '#/components/schemas/${endpoint.requestBody.get}'\n")
}
// Responses
yaml.append(" responses:\n")
yaml.append(" '200':\n")
yaml.append(" description: Success\n")
if (endpoint.responseBody.isDefined) {
yaml.append(" content:\n")
yaml.append(" application/json:\n")
yaml.append(" schema:\n")
yaml.append(s" $$ref: '#/components/schemas/${endpoint.responseBody.get}'\n")
}
// Error responses
if (endpoint.errorCodes.nonEmpty) {
endpoint.errorCodes.filter(_.contains("400")).foreach { _ =>
yaml.append(" '400':\n")
yaml.append(" description: Bad Request\n")
}
endpoint.errorCodes.filter(_.contains("401")).foreach { _ =>
yaml.append(" '401':\n")
yaml.append(" description: Unauthorized\n")
}
endpoint.errorCodes.filter(_.contains("404")).foreach { _ =>
yaml.append(" '404':\n")
yaml.append(" description: Not Found\n")
}
}
// Security
if (endpoint.roles.nonEmpty || !endpoint.errorCodes.exists(_.contains("AuthenticatedUserIsRequired"))) {
yaml.append(" security:\n")
yaml.append(" - DirectLogin: []\n")
yaml.append(" - GatewayLogin: []\n")
yaml.append(" - OAuth2: []\n")
}
yaml.append("\n")
}
}
yaml.toString()
}
def convertPathToOpenAPI(obpPath: String): String = {
obpPath.replaceAll("([A-Z_]+)", "{$1}")
.replaceAll("\\{([A-Z_]+)\\}", "{${1.toLowerCase}}")
.replaceAll("_", "-")
}
def extractPathParameters(path: String): List[String] = {
val paramPattern = """([A-Z_]+)""".r
paramPattern.findAllMatchIn(path).map(_.group(1).toLowerCase.replace("_", "-")).toList
}
}