forked from OpenBankProject/OBP-API
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathResourceDocsAPIMethods.scala
More file actions
1259 lines (1118 loc) · 59.4 KB
/
ResourceDocsAPIMethods.scala
File metadata and controls
1259 lines (1118 loc) · 59.4 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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package code.api.ResourceDocs1_4_0
import code.api.Constant.{GET_DYNAMIC_RESOURCE_DOCS_TTL, GET_STATIC_RESOURCE_DOCS_TTL, HostName, PARAM_LOCALE}
import code.api.OBPRestHelper
import code.api.cache.Caching
import code.api.dynamic.endpoint.OBPAPIDynamicEndpoint
import code.api.dynamic.entity.OBPAPIDynamicEntity
import code.api.util.APIUtil._
import code.api.util.ApiRole.{canReadDynamicResourceDocsAtOneBank, canReadResourceDoc}
import code.api.util.ApiTag._
import code.api.util.ExampleValue.endpointMappingRequestBodyExample
import code.api.util.FutureUtil.EndpointContext
import code.api.util.NewStyle.HttpCode
import code.api.util._
import code.api.util.YAMLUtils
import code.api.v1_4_0.JSONFactory1_4_0.ResourceDocsJson
import code.api.v1_4_0.{APIMethods140, JSONFactory1_4_0, OBPAPI1_4_0}
import code.api.v2_2_0.{APIMethods220, OBPAPI2_2_0}
import code.api.v3_0_0.OBPAPI3_0_0
import code.api.v3_1_0.OBPAPI3_1_0
import code.api.v4_0_0.{APIMethods400, OBPAPI4_0_0}
import code.api.v5_0_0.OBPAPI5_0_0
import code.api.v5_1_0.OBPAPI5_1_0
import code.api.v6_0_0.OBPAPI6_0_0
import code.apicollectionendpoint.MappedApiCollectionEndpointsProvider
import code.util.Helper
import code.util.Helper.{MdcLoggable, ObpS, SILENCE_IS_GOLDEN}
import com.github.dwickern.macros.NameOf.nameOf
import com.openbankproject.commons.model.enums.ContentParam
import com.openbankproject.commons.model.enums.ContentParam.{ALL, DYNAMIC, STATIC}
import com.openbankproject.commons.model.{BankId, ListResult, User}
import com.openbankproject.commons.util.ApiStandards._
import com.openbankproject.commons.util.{ApiVersion, ScannedApiVersion}
import net.liftweb.common.{Box, Empty, Full}
import net.liftweb.http.{LiftRules, S}
import net.liftweb.http.{InMemoryResponse, LiftRules, PlainTextResponse}
import net.liftweb.json
import net.liftweb.json.JsonAST.{JField, JString, JValue}
import net.liftweb.json._
import java.util.concurrent.ConcurrentHashMap
import scala.collection.immutable
import scala.collection.immutable.{List, Nil}
import scala.concurrent.Future
// JObject creation
import code.api.v1_2_1.{APIMethods121, OBPAPI1_2_1}
import code.api.v1_3_0.{APIMethods130, OBPAPI1_3_0}
import code.api.v2_0_0.{APIMethods200, OBPAPI2_0_0}
import code.api.v2_1_0.{APIMethods210, OBPAPI2_1_0}
import scala.collection.mutable.ArrayBuffer
// So we can include resource docs from future versions
import code.api.util.ErrorMessages._
import code.util.Helper.booleanToBox
import com.openbankproject.commons.ExecutionContext.Implicits.global
trait ResourceDocsAPIMethods extends MdcLoggable with APIMethods220 with APIMethods210 with APIMethods200 with APIMethods140 with APIMethods130 with APIMethods121{
//needs to be a RestHelper to get access to JsonGet, JsonPost, etc.
// We add previous APIMethods so we have access to the Resource Docs
self: OBPRestHelper =>
val ImplementationsResourceDocs = new Object() {
val localResourceDocs = ArrayBuffer[ResourceDoc]()
val implementedInApiVersion = ApiVersion.v1_4_0
implicit val formats = CustomJsonFormats.rolesMappedToClassesFormats
// avoid repeat execute method getSpecialInstructions, here save the calculate results.
private val specialInstructionMap = new ConcurrentHashMap[String, Option[String]]()
// Find any special instructions for partialFunctionName
def getSpecialInstructions(partialFunctionName: String): Option[String] = {
logger.trace(s"ResourceDocsAPIMethods.getSpecialInstructions.specialInstructionMap.size is ${specialInstructionMap.size()}")
specialInstructionMap.computeIfAbsent(partialFunctionName, _ => {
// The files should be placed in a folder called special_instructions_for_resources folder inside the src resources folder
// Each file should match a partial function name or it will be ignored.
// The format of the file should be mark down.
val filename = s"/special_instructions_for_resources/${partialFunctionName}.md"
logger.trace(s"getSpecialInstructions getting $filename")
val source = LiftRules.loadResourceAsString(filename)
logger.trace(s"getSpecialInstructions source is $source")
source match {
case Full(payload) =>
logger.trace(s"getSpecialInstructions payload is $payload")
Some(payload)
case _ =>
logger.trace(s"getSpecialInstructions Could not find / load $filename")
None
}
})
}
def getResourceDocsList(requestedApiVersion : ApiVersion) : Option[List[ResourceDoc]] =
{
// Determine if the partialFunctionName is due to be "featured" in API Explorer etc.
// "Featured" means shown at the top of the list or so.
def getIsFeaturedApi(partialFunctionName: String) : Boolean = {
val partialFunctionNames = APIUtil.getPropsValue("featured_apis") match {
case Full(v) =>
v.split(",").map(_.trim).toList
case _ =>
List()
}
partialFunctionNames.filter(_ == partialFunctionName).length > 0
}
// Return a different list of resource docs depending on the version being called.
// For instance 1_3_0 will have the docs for 1_3_0 and 1_2_1 (when we started adding resource docs) etc.
logger.debug(s"getResourceDocsList says requestedApiVersion is $requestedApiVersion")
val resourceDocs = requestedApiVersion match {
case ApiVersion.v7_0_0 => code.api.v7_0_0.Http4s700.resourceDocs
case ApiVersion.v6_0_0 => OBPAPI6_0_0.allResourceDocs
case ApiVersion.v5_1_0 => OBPAPI5_1_0.allResourceDocs
case ApiVersion.v5_0_0 => OBPAPI5_0_0.allResourceDocs
case ApiVersion.v4_0_0 => OBPAPI4_0_0.allResourceDocs
case ApiVersion.v3_1_0 => OBPAPI3_1_0.allResourceDocs
case ApiVersion.v3_0_0 => OBPAPI3_0_0.allResourceDocs
case ApiVersion.v2_2_0 => OBPAPI2_2_0.allResourceDocs
case ApiVersion.v2_1_0 => OBPAPI2_1_0.allResourceDocs
case ApiVersion.v2_0_0 => Implementations2_0_0.resourceDocs ++ Implementations1_4_0.resourceDocs ++ Implementations1_3_0.resourceDocs ++ Implementations1_2_1.resourceDocs
case ApiVersion.v1_4_0 => Implementations1_4_0.resourceDocs ++ Implementations1_3_0.resourceDocs ++ Implementations1_2_1.resourceDocs
case ApiVersion.v1_3_0 => Implementations1_3_0.resourceDocs ++ Implementations1_2_1.resourceDocs
case ApiVersion.v1_2_1 => Implementations1_2_1.resourceDocs
case ApiVersion.`dynamic-endpoint` => OBPAPIDynamicEndpoint.allResourceDocs
case ApiVersion.`dynamic-entity` => OBPAPIDynamicEntity.allResourceDocs
case version: ScannedApiVersion => ScannedApis.versionMapScannedApis(version).allResourceDocs
case _ => ArrayBuffer.empty[ResourceDoc]
}
logger.debug(s"There are ${resourceDocs.length} resource docs available to $requestedApiVersion")
val versionRoutes = requestedApiVersion match {
case ApiVersion.v7_0_0 => Nil
case ApiVersion.v6_0_0 => OBPAPI6_0_0.routes
case ApiVersion.v5_1_0 => OBPAPI5_1_0.routes
case ApiVersion.v5_0_0 => OBPAPI5_0_0.routes
case ApiVersion.v4_0_0 => OBPAPI4_0_0.routes
case ApiVersion.v3_1_0 => OBPAPI3_1_0.routes
case ApiVersion.v3_0_0 => OBPAPI3_0_0.routes
case ApiVersion.v2_2_0 => OBPAPI2_2_0.routes
case ApiVersion.v2_1_0 => OBPAPI2_1_0.routes
case ApiVersion.v2_0_0 => OBPAPI2_0_0.routes
case ApiVersion.v1_4_0 => OBPAPI1_4_0.routes
case ApiVersion.v1_3_0 => OBPAPI1_3_0.routes
case ApiVersion.v1_2_1 => OBPAPI1_2_1.routes
case ApiVersion.`dynamic-endpoint` => OBPAPIDynamicEndpoint.routes
case ApiVersion.`dynamic-entity` => OBPAPIDynamicEntity.routes
case version: ScannedApiVersion => ScannedApis.versionMapScannedApis(version).routes
case _ => Nil
}
logger.debug(s"There are ${versionRoutes.length} routes available to $requestedApiVersion")
// We only want the resource docs for which a API route exists else users will see 404s
// Get a list of the partial function classes represented in the routes available to this version.
val versionRoutesClasses = versionRoutes.map { vr => vr.getClass }
// Only return the resource docs that have available routes
val activeResourceDocs = requestedApiVersion match {
case ApiVersion.v7_0_0 => resourceDocs
case _ => resourceDocs.filter(rd => versionRoutesClasses.contains(rd.partialFunction.getClass))
}
logger.debug(s"There are ${activeResourceDocs.length} resource docs available to $requestedApiVersion")
val activePlusLocalResourceDocs = ArrayBuffer[ResourceDoc]()
activePlusLocalResourceDocs ++= activeResourceDocs
requestedApiVersion match
{
// only `obp` standard show the `localResourceDocs`
case version: ScannedApiVersion
if(version.apiStandard == obp.toString) =>
activePlusLocalResourceDocs ++= localResourceDocs
case _ => ; // all other standards only show their own apis.
}
// Add any featured status and special instructions from Props
val theResourceDocs = for {
x <- activePlusLocalResourceDocs
y = x.copy(
isFeatured = getIsFeaturedApi(x.partialFunctionName),
specialInstructions = getSpecialInstructions(x.partialFunctionName),
requestUrl = s"/${x.implementedInApiVersion.urlPrefix}/${x.implementedInApiVersion.vDottedApiVersion}${x.requestUrl}", // This is the "implemented" in url
specifiedUrl = Some(s"/${x.implementedInApiVersion.urlPrefix}/${requestedApiVersion.vDottedApiVersion}${x.requestUrl}"), // This is the "specified" in url when we call the resourceDoc api
)
} yield {
y.connectorMethods = x.connectorMethods // scala language bug, var field can't be kept when do copy, it must reset itself manually.
y
}
logger.debug(s"There are ${theResourceDocs.length} resource docs (including local) available to $requestedApiVersion")
// Sort by endpoint, verb. Thus / is shown first then /accounts and /banks etc. Seems to read quite well like that.
Some(theResourceDocs.toList.sortBy(rd => (rd.requestUrl, rd.requestVerb)))
}
// TODO constrain version?
// strip the leading v
def cleanApiVersionString (version: String) : String = {
version.stripPrefix("v").stripPrefix("V")
}
/**
*
* @param requestedApiVersion
* @param resourceDocTags
* @param partialFunctionNames
* @param contentParam if this is Some(`true`), only show dynamic endpoints, if Some(`false`), only show static. If it is None, we will show all. default is None
* @return
*/
def getStaticResourceDocsObpCached(
requestedApiVersionString: String,
resourceDocTags: Option[List[ResourceDocTag]],
partialFunctionNames: Option[List[String]],
locale: Option[String],
isVersion4OrHigher: Boolean
) = {
logger.debug(s"Generating OBP-getStaticResourceDocsObpCached requestedApiVersion is $requestedApiVersionString")
val requestedApiVersion = ApiVersionUtils.valueOf(requestedApiVersionString)
resourceDocsToResourceDocJson(getResourceDocsList(requestedApiVersion), resourceDocTags, partialFunctionNames, isVersion4OrHigher, locale)
}
/**
*
* @param requestedApiVersion
* @param resourceDocTags
* @param partialFunctionNames
* @param contentParam if this is Some(`true`), only show dynamic endpoints, if Some(`false`), only show static. If it is None, we will show all. default is None
* @return
*/
def getAllResourceDocsObpCached(
requestedApiVersionString: String,
resourceDocTags: Option[List[ResourceDocTag]],
partialFunctionNames: Option[List[String]],
locale: Option[String],
contentParam: Option[ContentParam],
isVersion4OrHigher: Boolean
) = {
logger.debug(s"Generating getAllResourceDocsObpCached-Docs requestedApiVersion is $requestedApiVersionString")
val requestedApiVersion = ApiVersionUtils.valueOf(requestedApiVersionString)
val dynamicDocs = allDynamicResourceDocs
.map(it => it.specifiedUrl match {
case Some(_) => it
case _ =>
it.specifiedUrl = if (it.partialFunctionName.startsWith("dynamicEntity")) Some(s"/${it.implementedInApiVersion.urlPrefix}/${ApiVersion.`dynamic-entity`}${it.requestUrl}") else Some(s"/${it.implementedInApiVersion.urlPrefix}/${ApiVersion.`dynamic-endpoint`}${it.requestUrl}")
it
})
val filteredDocs = resourceDocTags match {
// We have tags
case Some(tags) => {
// This can create duplicates to use toSet below
for {
r <- dynamicDocs
t <- tags
if r.tags.contains(t)
} yield {
r
}
}
// tags param was not mentioned in url or was empty, so return all
case None => dynamicDocs
}
val staticDocs = getResourceDocsList(requestedApiVersion)
val allDocs = staticDocs.map(_ ++ filteredDocs)
resourceDocsToResourceDocJson(allDocs, resourceDocTags, partialFunctionNames, isVersion4OrHigher, locale)
}
def getResourceDocsObpDynamicCached(
resourceDocTags: Option[List[ResourceDocTag]],
partialFunctionNames: Option[List[String]],
locale: Option[String],
bankId: Option[String],
isVersion4OrHigher: Boolean
) = {
val dynamicDocs = allDynamicResourceDocs
.filter(rd => if (bankId.isDefined) rd.createdByBankId == bankId else true)
.map(it => it.specifiedUrl match {
case Some(_) => it
case _ =>
it.specifiedUrl = if (it.partialFunctionName.startsWith("dynamicEntity")) Some(s"/${it.implementedInApiVersion.urlPrefix}/${ApiVersion.`dynamic-entity`}${it.requestUrl}") else Some(s"/${it.implementedInApiVersion.urlPrefix}/${ApiVersion.`dynamic-endpoint`}${it.requestUrl}")
it
})
.toList
val filteredDocs = resourceDocTags match {
// We have tags
case Some(tags) => {
// This can create duplicates to use toSet below
for {
r <- dynamicDocs
t <- tags
if r.tags.contains(t)
} yield {
r
}
}
// tags param was not mentioned in url or was empty, so return all
case None => dynamicDocs
}
resourceDocsToResourceDocJson(Some(filteredDocs), resourceDocTags, partialFunctionNames, isVersion4OrHigher, locale)
}
private def resourceDocsToResourceDocJson(
rd: Option[List[ResourceDoc]],
resourceDocTags: Option[List[ResourceDocTag]],
partialFunctionNames: Option[List[String]],
isVersion4OrHigher: Boolean,
locale: Option[String]
): Option[ResourceDocsJson] = {
for {
resourceDocs <- rd
} yield {
// Filter
val rdFiltered = ResourceDocsAPIMethodsUtil.filterResourceDocs(resourceDocs, resourceDocTags, partialFunctionNames)
// Format the data as json
JSONFactory1_4_0.createResourceDocsJson(rdFiltered, isVersion4OrHigher, locale)
}
}
def getResourceDocsDescription(isBankLevelResourceDoc: Boolean) = {
val endpointBankIdPath = if (isBankLevelResourceDoc) "/banks/BANK_ID" else ""
s"""Get documentation about the RESTful resources on this server including example bodies for POST and PUT requests.
|
|This is the native data format used to document OBP endpoints. Each endpoint has a Resource Doc (a Scala case class) defined in the source code.
|
| This endpoint is used by OBP API Explorer to display and work with the API documentation.
|
| Most (but not all) fields are also available in swagger format. (The Swagger endpoint is built from Resource Docs.)
|
| API_VERSION is the version you want documentation about e.g. v3.0.0
|
| You may filter this endpoint with tags parameter e.g. ?tags=Account,Bank
|
| You may filter this endpoint with functions parameter e.g. ?functions=enableDisableConsumers,getConnectorMetrics
|
| For possible function values, see implemented_by.function in the JSON returned by this endpoint or the OBP source code or the footer of the API Explorer which produces a comma separated list of functions that reflect the server or filtering by API Explorer based on tags etc.
|
| You may filter this endpoint using the 'content' url parameter, e.g. ?content=dynamic
| if set content=dynamic, only show dynamic endpoints, if content=static, only show the static endpoints. if omit this parameter, we will show all the endpoints.
|
| You may need some other language resource docs, now we support en_GB and es_ES at the moment.
|
| You can filter with api-collection-id, but api-collection-id can not be used with others together. If api-collection-id is used in URL, it will ignore all other parameters.
|
|See the Resource Doc endpoint for more information.
|
|Note: Dynamic Resource Docs are cached, TTL is ${GET_DYNAMIC_RESOURCE_DOCS_TTL} seconds
| Static Resource Docs are cached, TTL is ${GET_STATIC_RESOURCE_DOCS_TTL} seconds
|
|
|Following are more examples:
|${getObpApiRoot}/v4.0.0$endpointBankIdPath/resource-docs/v4.0.0/obp
|${getObpApiRoot}/v4.0.0$endpointBankIdPath/resource-docs/v4.0.0/obp?tags=Account,Bank
|${getObpApiRoot}/v4.0.0$endpointBankIdPath/resource-docs/v4.0.0/obp?functions=getBanks,bankById
|${getObpApiRoot}/v4.0.0$endpointBankIdPath/resource-docs/v4.0.0/obp?locale=es_ES
|${getObpApiRoot}/v4.0.0$endpointBankIdPath/resource-docs/v4.0.0/obp?content=static,dynamic,all
|${getObpApiRoot}/v4.0.0$endpointBankIdPath/resource-docs/v4.0.0/obp?api-collection-id=4e866c86-60c3-4268-a221-cb0bbf1ad221
|
|<ul>
|<li> operation_id is concatenation of "v", version and function and should be unique (used for DOM element IDs etc. maybe used to link to source code) </li>
|<li> version references the version that the API call is defined in.</li>
|<li> function is the (scala) partial function that implements this endpoint. It is unique per version of the API.</li>
|<li> request_url is empty for the root call, else the path. It contains the standard prefix (e.g. /obp) and the implemented version (the version where this endpoint was defined) e.g. /obp/v1.2.0/resource</li>
|<li> specified_url (recommended to use) is empty for the root call, else the path. It contains the standard prefix (e.g. /obp) and the version specified in the call e.g. /obp/v3.1.0/resource. In OBP, endpoints are first made available at the request_url, but the same resource (function call) is often made available under later versions (specified_url). To access the latest version of all endpoints use the latest version available on your OBP instance e.g. /obp/v3.1.0 - To get the original version use the request_url. We recommend to use the specified_url since non semantic improvements are more likely to be applied to later implementations of the call.</li>
|<li> summary is a short description inline with the swagger terminology. </li>
|<li> description may contain html markup (generated from markdown on the server).</li>
|</ul>
"""
}
localResourceDocs += ResourceDoc(
getResourceDocsObp,
implementedInApiVersion,
"getResourceDocsObp",
"GET",
"/resource-docs/API_VERSION/obp",
"Get Resource Docs.",
getResourceDocsDescription(false),
EmptyBody,
EmptyBody,
UnknownError :: Nil,
List(apiTagDocumentation, apiTagApi),
Some(List(canReadResourceDoc))
)
def resourceDocsRequireRole = APIUtil.getPropsAsBoolValue("resource_docs_requires_role", false)
// Provides resource documents so that API Explorer (or other apps) can display API documentation
// Note: description uses html markup because original markdown doesn't easily support "_" and there are multiple versions of markdown.
lazy val getResourceDocsObp : OBPEndpoint = {
case "resource-docs" :: requestedApiVersionString :: "obp" :: Nil JsonGet _ => {
val (tags, partialFunctions, locale, contentParam, apiCollectionIdParam) = ResourceDocsAPIMethodsUtil.getParams()
cc =>
implicit val ec = EndpointContext(Some(cc))
getApiLevelResourceDocs(cc,requestedApiVersionString, tags, partialFunctions, locale, contentParam, apiCollectionIdParam,false)
}
}
localResourceDocs += ResourceDoc(
getResourceDocsObpV400,
implementedInApiVersion,
nameOf(getResourceDocsObpV400),
"GET",
"/resource-docs/API_VERSION/obp",
"Get Resource Docs",
getResourceDocsDescription(false),
EmptyBody,
EmptyBody,
UnknownError :: Nil,
List(apiTagDocumentation, apiTagApi),
Some(List(canReadResourceDoc))
)
lazy val getResourceDocsObpV400 : OBPEndpoint = {
case "resource-docs" :: requestedApiVersionString :: "obp" :: Nil JsonGet _ => {
val (tags, partialFunctions, locale, contentParam, apiCollectionIdParam) = ResourceDocsAPIMethodsUtil.getParams()
cc =>
implicit val ec = EndpointContext(Some(cc))
getApiLevelResourceDocs(cc,requestedApiVersionString, tags, partialFunctions, locale, contentParam, apiCollectionIdParam,true)
}
}
//API level just mean, this response will be forward to liftweb directly.
private def getApiLevelResourceDocs(
cc: CallContext,
requestedApiVersionString: String,
tags: Option[List[ResourceDocTag]],
partialFunctions: Option[List[String]],
locale: Option[String],
contentParam: Option[ContentParam],
apiCollectionIdParam: Option[String],
isVersion4OrHigher: Boolean,
) = {
for {
(u: Box[User], callContext: Option[CallContext]) <- resourceDocsRequireRole match {
case false => anonymousAccess(cc)
case true => authenticatedAccess(cc) // If set resource_docs_requires_role=true, we need check the authentication
}
_ <- resourceDocsRequireRole match {
case false => Future(())
case true => // If set resource_docs_requires_role=true, we need check the roles as well
NewStyle.function.hasAtLeastOneEntitlement(failMsg = UserHasMissingRoles + canReadResourceDoc.toString)("", u.map(_.userId).getOrElse(""), ApiRole.canReadResourceDoc :: Nil, cc.callContext)
}
requestedApiVersion <- NewStyle.function.tryons(s"$InvalidApiVersionString $requestedApiVersionString", 400, callContext) {ApiVersionUtils.valueOf(requestedApiVersionString)}
_ <- Helper.booleanToFuture(s"$ApiVersionNotSupported $requestedApiVersionString", 400, callContext)(versionIsAllowed(requestedApiVersion))
_ <- if (locale.isDefined) {
Helper.booleanToFuture(failMsg = s"$InvalidLocale Current Locale is ${locale.get}" intern(), cc = cc.callContext) {
APIUtil.obpLocaleValidation(locale.get) == SILENCE_IS_GOLDEN
}
} else {
Future.successful(true)
}
cacheKey = APIUtil.createResourceDocCacheKey(
None,
requestedApiVersionString,
tags,
partialFunctions,
locale,
contentParam,
apiCollectionIdParam,
Some(isVersion4OrHigher)
)
json <- locale match {
case _ if (apiCollectionIdParam.isDefined) =>
NewStyle.function.tryons(s"$UnknownError Can not prepare OBP resource docs.", 500, callContext) {
val operationIds = MappedApiCollectionEndpointsProvider.getApiCollectionEndpoints(apiCollectionIdParam.getOrElse("")).map(_.operationId).map(getObpFormatOperationId)
val resourceDocs = ResourceDoc.getResourceDocs(operationIds)
val resourceDocsJson = JSONFactory1_4_0.createResourceDocsJson(resourceDocs, isVersion4OrHigher, locale)
val resourceDocsJsonJValue = Full(resourceDocsJsonToJsonResponse(resourceDocsJson))
resourceDocsJsonJValue.map(successJsonResponse(_))
}
case _ =>
contentParam match {
case Some(DYNAMIC) =>{
NewStyle.function.tryons(s"$UnknownError Can not prepare OBP resource docs.", 500, callContext) {
val cacheValueFromRedis = Caching.getDynamicResourceDocCache(cacheKey)
val dynamicDocs: Box[JValue] =
if (cacheValueFromRedis.isDefined) {
Full(json.parse(cacheValueFromRedis.get))
} else {
val resourceDocJson = getResourceDocsObpDynamicCached(tags, partialFunctions, locale, None, false)
val resourceDocJsonJValue = resourceDocJson.map(resourceDocsJsonToJsonResponse).head
val jsonString = json.compactRender(resourceDocJsonJValue)
Caching.setDynamicResourceDocCache(cacheKey, jsonString)
Full(resourceDocJsonJValue)
}
dynamicDocs.map(successJsonResponse(_))
}
}
case Some(STATIC) => {
NewStyle.function.tryons(s"$UnknownError Can not prepare OBP resource docs.", 500, callContext) {
val cacheValueFromRedis = Caching.getStaticResourceDocCache(cacheKey)
val staticDocs: Box[JValue] =
if (cacheValueFromRedis.isDefined) {
Full(json.parse(cacheValueFromRedis.get))
} else {
val resourceDocJson = getStaticResourceDocsObpCached(requestedApiVersionString, tags, partialFunctions, locale, isVersion4OrHigher)
val resourceDocJsonJValue = resourceDocJson.map(resourceDocsJsonToJsonResponse).head
val jsonString = json.compactRender(resourceDocJsonJValue)
Caching.setStaticResourceDocCache(cacheKey, jsonString)
Full(resourceDocJsonJValue)
}
staticDocs.map(successJsonResponse(_))
}
}
case _ => {
NewStyle.function.tryons(s"$UnknownError Can not prepare OBP resource docs.", 500, callContext) {
val cacheValueFromRedis = Caching.getAllResourceDocCache(cacheKey)
val bothStaticAndDyamicDocs: Box[JValue] =
if (cacheValueFromRedis.isDefined) {
Full(json.parse(cacheValueFromRedis.get))
} else {
val resourceDocJson = getAllResourceDocsObpCached(requestedApiVersionString, tags, partialFunctions, locale, contentParam, isVersion4OrHigher)
val resourceDocJsonJValue = resourceDocJson.map(resourceDocsJsonToJsonResponse).head
val jsonString = json.compactRender(resourceDocJsonJValue)
Caching.setAllResourceDocCache(cacheKey, jsonString)
Full(resourceDocJsonJValue)
}
bothStaticAndDyamicDocs.map(successJsonResponse(_))
}
}
}
}
} yield {
(json, HttpCode.`200`(callContext))
}
}
localResourceDocs += ResourceDoc(
getBankLevelDynamicResourceDocsObp,
implementedInApiVersion,
nameOf(getBankLevelDynamicResourceDocsObp),
"GET",
"/banks/BANK_ID/resource-docs/API_VERSION/obp",
"Get Bank Level Dynamic Resource Docs.",
getResourceDocsDescription(true),
EmptyBody,
EmptyBody,
UnknownError :: Nil,
List(apiTagDocumentation, apiTagApi),
Some(List(canReadDynamicResourceDocsAtOneBank))
)
// Provides resource documents so that API Explorer (or other apps) can display API documentation
// Note: description uses html markup because original markdown doesn't easily support "_" and there are multiple versions of markdown.
def getBankLevelDynamicResourceDocsObp : OBPEndpoint = {
case "banks" :: bankId :: "resource-docs" :: requestedApiVersionString :: "obp" :: Nil JsonGet _ => {
val (tags, partialFunctions, locale, contentParam, apiCollectionIdParam) = ResourceDocsAPIMethodsUtil.getParams()
cc =>
for {
(u: Box[User], callContext: Option[CallContext]) <- resourceDocsRequireRole match {
case false => anonymousAccess(cc)
case true => authenticatedAccess(cc) // If set resource_docs_requires_role=true, we need check the authentication
}
_ <- if (locale.isDefined) {
Helper.booleanToFuture(failMsg = s"$InvalidLocale Current Locale is ${locale.get}" intern(), cc = cc.callContext) {
APIUtil.obpLocaleValidation(locale.get) == SILENCE_IS_GOLDEN
}
} else {
Future.successful(true)
}
(_, callContext) <- NewStyle.function.getBank(BankId(bankId), Option(cc))
_ <- resourceDocsRequireRole match {
case false => Future(())
case true => // If set resource_docs_requires_role=true, we need check the the roles as well
NewStyle.function.hasAtLeastOneEntitlement(failMsg = UserHasMissingRoles + ApiRole.canReadDynamicResourceDocsAtOneBank.toString)(
bankId, u.map(_.userId).getOrElse(""), ApiRole.canReadDynamicResourceDocsAtOneBank::Nil, cc.callContext
)
}
requestedApiVersion <- NewStyle.function.tryons(s"$InvalidApiVersionString $requestedApiVersionString", 400, callContext) {ApiVersionUtils.valueOf(requestedApiVersionString)}
cacheKey = APIUtil.createResourceDocCacheKey(
Some(bankId),
requestedApiVersionString,
tags,
partialFunctions,
locale,
contentParam,
apiCollectionIdParam,
None)
json <- NewStyle.function.tryons(s"$UnknownError Can not create dynamic resource docs.", 400, callContext) {
val cacheValueFromRedis = Caching.getDynamicResourceDocCache(cacheKey)
if (cacheValueFromRedis.isDefined) {
json.parse(cacheValueFromRedis.get)
} else {
val resourceDocJson = getResourceDocsObpDynamicCached(tags, partialFunctions, locale, None, false)
val resourceDocJsonJValue = resourceDocJson.map(resourceDocsJsonToJsonResponse).head
val jsonString = json.compactRender(resourceDocJsonJValue)
Caching.setDynamicResourceDocCache(cacheKey, jsonString)
resourceDocJsonJValue
}
}
} yield {
(Full(json), HttpCode.`200`(callContext))
}
}
}
localResourceDocs += ResourceDoc(
getResourceDocsSwagger,
implementedInApiVersion,
"getResourceDocsSwagger",
"GET",
"/resource-docs/API_VERSION/swagger",
"Get Swagger documentation",
s"""Returns documentation about the RESTful resources on this server in Swagger format.
|
|API_VERSION is the version you want documentation about e.g. v3.0.0
|
|You may filter this endpoint using the 'tags' url parameter e.g. ?tags=Account,Bank
|
|(All endpoints are given one or more tags which for used in grouping)
|
|You may filter this endpoint using the 'functions' url parameter e.g. ?functions=getBanks,bankById
|
|(Each endpoint is implemented in the OBP Scala code by a 'function')
|
|See the Resource Doc endpoint for more information.
|
| Note: Resource Docs are cached, TTL is ${GET_DYNAMIC_RESOURCE_DOCS_TTL} seconds
|
|Following are more examples:
|${getObpApiRoot}/v3.1.0/resource-docs/v3.1.0/swagger
|${getObpApiRoot}/v3.1.0/resource-docs/v3.1.0/swagger?tags=Account,Bank
|${getObpApiRoot}/v3.1.0/resource-docs/v3.1.0/swagger?functions=getBanks,bankById
|${getObpApiRoot}/v3.1.0/resource-docs/v3.1.0/swagger?tags=Account,Bank,PSD2&functions=getBanks,bankById
|
""",
EmptyBody,
EmptyBody,
UnknownError :: Nil,
List(apiTagDocumentation, apiTagApi)
)
// Note: Swagger format requires special character escaping because it builds JSON via string concatenation (unlike OBP/OpenAPI formats which use case class serialization)
def getResourceDocsSwagger : OBPEndpoint = {
case "resource-docs" :: requestedApiVersionString :: "swagger" :: Nil JsonGet _ => {
cc => {
implicit val ec = EndpointContext(Some(cc))
val (resourceDocTags, partialFunctions, locale, contentParam, apiCollectionIdParam) = ResourceDocsAPIMethodsUtil.getParams()
for {
requestedApiVersion <- NewStyle.function.tryons(s"$InvalidApiVersionString Current Version is $requestedApiVersionString", 400, cc.callContext) {
ApiVersionUtils.valueOf(requestedApiVersionString)
}
_ <- Helper.booleanToFuture(failMsg = s"$ApiVersionNotSupported Current Version is $requestedApiVersionString", cc=cc.callContext) {
versionIsAllowed(requestedApiVersion)
}
_ <- if (locale.isDefined) {
Helper.booleanToFuture(failMsg = s"$InvalidLocale Current Locale is ${locale.get}" intern(), cc = cc.callContext) {
APIUtil.obpLocaleValidation(locale.get) == SILENCE_IS_GOLDEN
}
} else {
Future.successful(true)
}
isVersion4OrHigher = true
cacheKey = APIUtil.createResourceDocCacheKey(
None,
requestedApiVersionString,
resourceDocTags,
partialFunctions,
locale,
contentParam,
apiCollectionIdParam,
Some(isVersion4OrHigher)
)
cacheValueFromRedis = Caching.getStaticSwaggerDocCache(cacheKey)
swaggerJValue <- if (cacheValueFromRedis.isDefined) {
NewStyle.function.tryons(s"$UnknownError Can not convert internal swagger file from cache.", 400, cc.callContext) {json.parse(cacheValueFromRedis.get)}
} else {
NewStyle.function.tryons(s"$UnknownError Can not convert internal swagger file.", 400, cc.callContext) {
val resourceDocsJsonFiltered = locale match {
case _ if (apiCollectionIdParam.isDefined) =>
val operationIds = MappedApiCollectionEndpointsProvider.getApiCollectionEndpoints(apiCollectionIdParam.getOrElse("")).map(_.operationId).map(getObpFormatOperationId)
val resourceDocs = ResourceDoc.getResourceDocs(operationIds)
val resourceDocsJson = JSONFactory1_4_0.createResourceDocsJson(resourceDocs, isVersion4OrHigher, locale)
resourceDocsJson.resource_docs
case _ =>
contentParam match {
case Some(DYNAMIC) =>
getResourceDocsObpDynamicCached(resourceDocTags, partialFunctions, locale, None, isVersion4OrHigher).head.resource_docs
case Some(STATIC) => {
getStaticResourceDocsObpCached(requestedApiVersionString, resourceDocTags, partialFunctions, locale, isVersion4OrHigher).head.resource_docs
}
case _ => {
getAllResourceDocsObpCached(requestedApiVersionString, resourceDocTags, partialFunctions, locale, contentParam, isVersion4OrHigher).head.resource_docs
}
}
}
convertResourceDocsToSwaggerJvalueAndSetCache(cacheKey, requestedApiVersionString, resourceDocsJsonFiltered)
}
}
} yield {
(swaggerJValue, HttpCode.`200`(cc.callContext))
}
}
}
}
localResourceDocs += ResourceDoc(
getResourceDocsOpenAPI31,
implementedInApiVersion,
"getResourceDocsOpenAPI31",
"GET",
"/resource-docs/API_VERSION/openapi",
"Get OpenAPI 3.1 documentation",
s"""Returns documentation about the RESTful resources on this server in OpenAPI 3.1 format.
|
|API_VERSION is the version you want documentation about e.g. v6.0.0
|
|## Query Parameters
|
|You may filter this endpoint using the following optional query parameters:
|
|**tags** - Filter by endpoint tags (comma-separated list)
| • Example: ?tags=Account,Bank or ?tags=Account-Firehose
| • All endpoints are given one or more tags which are used for grouping
| • Empty values will return error OBP-10053
|
|**functions** - Filter by function names (comma-separated list)
| • Example: ?functions=getBanks,bankById
| • Each endpoint is implemented in the OBP Scala code by a 'function'
| • Empty values will return error OBP-10054
|
|**content** - Filter by endpoint type
| • Values: static, dynamic, all (case-insensitive)
| • static: Only show static/core API endpoints
| • dynamic: Only show dynamic/custom endpoints
| • all: Show both static and dynamic endpoints (default)
| • Invalid values will return error OBP-10052
|
|**locale** - Language for localized documentation
| • Example: ?locale=en_GB or ?locale=es_ES
| • Supported locales: en_GB, es_ES, ro_RO
| • Invalid locales will return error OBP-10041
|
|**api-collection-id** - Filter by API collection UUID
| • Example: ?api-collection-id=4e866c86-60c3-4268-a221-cb0bbf1ad221
| • Returns only endpoints belonging to the specified collection
| • Empty values will return error OBP-10055
|
|This endpoint generates OpenAPI 3.1 compliant documentation with modern JSON Schema support.
|
|For YAML format, use the corresponding endpoint: /resource-docs/API_VERSION/openapi.yaml
|
|See the Resource Doc endpoint for more information.
|
|Note: Resource Docs are cached, TTL is ${GET_DYNAMIC_RESOURCE_DOCS_TTL} seconds
|
|## Examples
|
|Basic usage:
|${getObpApiRoot}/v6.0.0/resource-docs/v6.0.0/openapi
|
|Filter by tags:
|${getObpApiRoot}/v6.0.0/resource-docs/v6.0.0/openapi?tags=Account,Bank
|${getObpApiRoot}/v6.0.0/resource-docs/v6.0.0/openapi?tags=Account-Firehose
|
|Filter by content type:
|${getObpApiRoot}/v6.0.0/resource-docs/v6.0.0/openapi?content=static
|${getObpApiRoot}/v6.0.0/resource-docs/v6.0.0/openapi?content=dynamic
|
|Filter by functions:
|${getObpApiRoot}/v6.0.0/resource-docs/v6.0.0/openapi?functions=getBanks,bankById
|
|Combine multiple parameters:
|${getObpApiRoot}/v6.0.0/resource-docs/v6.0.0/openapi?content=static&tags=Account-Firehose
|${getObpApiRoot}/v6.0.0/resource-docs/v6.0.0/openapi?tags=Account,Bank,PSD2&functions=getBanks,bankById
|${getObpApiRoot}/v6.0.0/resource-docs/v6.0.0/openapi?content=static&locale=en_GB&tags=Account
|
|Filter by API collection:
|${getObpApiRoot}/v6.0.0/resource-docs/v6.0.0/openapi?api-collection-id=4e866c86-60c3-4268-a221-cb0bbf1ad221
|
""",
EmptyBody,
EmptyBody,
InvalidApiVersionString ::
ApiVersionNotSupported ::
InvalidLocale ::
InvalidContentParameter ::
InvalidTagsParameter ::
InvalidFunctionsParameter ::
InvalidApiCollectionIdParameter ::
UnknownError :: Nil,
List(apiTagDocumentation, apiTagApi)
)
// Note: OpenAPI 3.1 YAML endpoint (/resource-docs/API_VERSION/openapi.yaml)
// is implemented using Lift's serve mechanism in ResourceDocs140.scala to properly
// handle YAML content type. It provides the same functionality as the JSON endpoint
// but returns OpenAPI documentation in YAML format instead of JSON.
/**
* OpenAPI 3.1 endpoint with comprehensive parameter validation.
*
* This endpoint generates OpenAPI 3.1 documentation with the following validated query parameters:
* - tags: Comma-separated list of tags to filter endpoints (e.g., ?tags=Account,Bank)
* - functions: Comma-separated list of function names to filter endpoints
* - content: Filter type - "static", "dynamic", or "all"
* - locale: Language code for localization (e.g., "en_GB", "es_ES")
* - api-collection-id: UUID to filter by specific API collection
*
* Parameter validation guards ensure:
* - Empty parameters (e.g., ?tags=) return 400 error
* - Invalid content values return 400 error with valid options
* - All parameters are properly trimmed and sanitized
*
* Examples:
* - ?content=static&tags=Account-Firehose
* - ?tags=Account,Bank&functions=getBanks,bankById
* - ?content=dynamic&locale=en_GB
*/
def getResourceDocsOpenAPI31 : OBPEndpoint = {
case "resource-docs" :: requestedApiVersionString :: "openapi" :: Nil JsonGet _ => {
cc => {
implicit val ec = EndpointContext(Some(cc))
// Early validation for empty parameters using underlying S to bypass ObpS filtering
if (S.param("tags").exists(_.trim.isEmpty)) {
Full(errorJsonResponse(InvalidTagsParameter, 400))
} else if (S.param("functions").exists(_.trim.isEmpty)) {
Full(errorJsonResponse(InvalidFunctionsParameter, 400))
} else if (S.param("api-collection-id").exists(_.trim.isEmpty)) {
Full(errorJsonResponse(InvalidApiCollectionIdParameter, 400))
} else {
val (resourceDocTags, partialFunctions, locale, contentParam, apiCollectionIdParam) = ResourceDocsAPIMethodsUtil.getParams()
for {
// Validate content parameter if provided
_ <- if (S.param("content").isDefined && contentParam.isEmpty) {
Helper.booleanToFuture(failMsg = InvalidContentParameter, cc = cc.callContext) {
false
}
} else {
Future.successful(true)
}
requestedApiVersion <- NewStyle.function.tryons(s"$InvalidApiVersionString Current Version is $requestedApiVersionString", 400, cc.callContext) {
ApiVersionUtils.valueOf(requestedApiVersionString)
}
_ <- Helper.booleanToFuture(failMsg = s"$ApiVersionNotSupported Current Version is $requestedApiVersionString", cc=cc.callContext) {
versionIsAllowed(requestedApiVersion)
}
_ <- if (locale.isDefined) {
Helper.booleanToFuture(failMsg = s"$InvalidLocale Current Locale is ${locale.get}" intern(), cc = cc.callContext) {
APIUtil.obpLocaleValidation(locale.get) == SILENCE_IS_GOLDEN
}
} else {
Future.successful(true)
}
isVersion4OrHigher = true
cacheKey = APIUtil.createResourceDocCacheKey(
Some("openapi31"),
requestedApiVersionString,
resourceDocTags,
partialFunctions,
locale,
contentParam,
apiCollectionIdParam,
Some(isVersion4OrHigher)
)
cacheValueFromRedis = Caching.getStaticSwaggerDocCache(cacheKey)
openApiJValue <- if (cacheValueFromRedis.isDefined) {
NewStyle.function.tryons(s"$UnknownError Can not convert internal openapi file from cache.", 400, cc.callContext) {json.parse(cacheValueFromRedis.get)}
} else {
NewStyle.function.tryons(s"$UnknownError Can not convert internal openapi file.", 400, cc.callContext) {
val resourceDocsJsonFiltered = locale match {
case _ if (apiCollectionIdParam.isDefined) =>
val operationIds = MappedApiCollectionEndpointsProvider.getApiCollectionEndpoints(apiCollectionIdParam.getOrElse("")).map(_.operationId).map(getObpFormatOperationId)
val resourceDocs = ResourceDoc.getResourceDocs(operationIds)
val resourceDocsJson = JSONFactory1_4_0.createResourceDocsJson(resourceDocs, isVersion4OrHigher, locale)
resourceDocsJson.resource_docs
case _ =>
contentParam match {
case Some(DYNAMIC) =>
getResourceDocsObpDynamicCached(resourceDocTags, partialFunctions, locale, None, isVersion4OrHigher).head.resource_docs
case Some(STATIC) => {
getStaticResourceDocsObpCached(requestedApiVersionString, resourceDocTags, partialFunctions, locale, isVersion4OrHigher).head.resource_docs
}
case _ => {
getAllResourceDocsObpCached(requestedApiVersionString, resourceDocTags, partialFunctions, locale, contentParam, isVersion4OrHigher).head.resource_docs
}
}
}
convertResourceDocsToOpenAPI31JvalueAndSetCache(cacheKey, requestedApiVersionString, resourceDocsJsonFiltered)
}
}
} yield {
(openApiJValue, HttpCode.`200`(cc.callContext))
}
}
}
}
}
// Note: The OpenAPI 3.1 YAML endpoint (/resource-docs/API_VERSION/openapi.yaml)
// is implemented using Lift's serve mechanism in ResourceDocs140.scala to properly
// handle YAML content type and response format, rather than as a standard OBPEndpoint.
def convertResourceDocsToOpenAPI31YAMLAndSetCache(cacheKey: String, requestedApiVersionString: String, resourceDocsJson: List[JSONFactory1_4_0.ResourceDocJson]) : String = {
logger.debug(s"Generating OpenAPI 3.1 YAML-convertResourceDocsToOpenAPI31YAMLAndSetCache requestedApiVersion is $requestedApiVersionString")
val hostname = HostName
val openApiDoc = code.api.ResourceDocs1_4_0.OpenAPI31JSONFactory.createOpenAPI31Json(resourceDocsJson, requestedApiVersionString, hostname)
val openApiJValue = code.api.ResourceDocs1_4_0.OpenAPI31JSONFactory.OpenAPI31JsonFormats.toJValue(openApiDoc)
val yamlString = YAMLUtils.jValueToYAMLSafe(openApiJValue, "# Error converting to YAML")
Caching.setStaticSwaggerDocCache(cacheKey, yamlString)
yamlString
}
private def convertResourceDocsToOpenAPI31JvalueAndSetCache(cacheKey: String, requestedApiVersionString: String, resourceDocsJson: List[JSONFactory1_4_0.ResourceDocJson]) : JValue = {
logger.debug(s"Generating OpenAPI 3.1-convertResourceDocsToOpenAPI31JvalueAndSetCache requestedApiVersion is $requestedApiVersionString")
val hostname = HostName
val openApiDoc = code.api.ResourceDocs1_4_0.OpenAPI31JSONFactory.createOpenAPI31Json(resourceDocsJson, requestedApiVersionString, hostname)
val openApiJValue = code.api.ResourceDocs1_4_0.OpenAPI31JSONFactory.OpenAPI31JsonFormats.toJValue(openApiDoc)
val jsonString = json.compactRender(openApiJValue)
Caching.setStaticSwaggerDocCache(cacheKey, jsonString)
openApiJValue
}
private def convertResourceDocsToSwaggerJvalueAndSetCache(cacheKey: String, requestedApiVersionString: String, resourceDocsJson: List[JSONFactory1_4_0.ResourceDocJson]) : JValue = {
logger.debug(s"Generating Swagger-getResourceDocsSwaggerAndSetCache requestedApiVersion is $requestedApiVersionString")
val swaggerDocJsonJValue = getResourceDocsSwagger(requestedApiVersionString, resourceDocsJson).head
val jsonString = json.compactRender(swaggerDocJsonJValue)
Caching.setStaticSwaggerDocCache(cacheKey, jsonString)
swaggerDocJsonJValue
}
// if not supply resourceDocs parameter, just get dynamic ResourceDocs swagger
private def getResourceDocsSwagger(
requestedApiVersionString : String,
resourceDocsJson: List[JSONFactory1_4_0.ResourceDocJson]
) : Box[JValue] = {
// build swagger and remove not used definitions
def buildSwagger(resourceDoc: SwaggerJSONFactory.SwaggerResourceDoc, definitions: json.JValue) = {
val jValue = Extraction.decompose(resourceDoc)
val JObject(pathsRef) = definitions \\ "$ref"
val JObject(definitionsRef) = jValue \\ "$ref"
val RefRegx = "#/definitions/([^/]+)".r
val allRefTypeName: Set[String] = Set(pathsRef, definitionsRef).flatMap { fields =>
fields.collect {
case JField(_, JString(RefRegx(v))) => v
}
}
// filter out all not used definitions
val usedDefinitions = {
val JObject(fields) = definitions \ "definitions"
JObject(
JField("definitions",
JObject(
fields.collect {
case jf @JField(name, _) if allRefTypeName.contains(name) => jf
}
)
) :: Nil