OpenAPI Support
The XData server can optionally provide a JSON file containing the OpenAPI Specification (OAS, formerly Swagger) for your whole server API. This opens up a lot of possibilities; usage of several tools of the OpenAPI ecosystem, like:
- Swagger UI: web front-end to describe and test your API
- Redoc: documentation generator for your API
- OpenAPI Generator: generate API clients for many different languages and plataforms
OpenAPI document
The main OpenAPI feature in XData is the generation of the OpenAPI document automatically from your API. This document fully describes your API using the standard OpenAPI Specification (OAS) and can be used in several different ways.
To enable OpenAPI support in your server (i.e, to tell XData to generate the OpenAPI document), just set the property
SwaggerOptions.Enabled
to true in your TXDataServer
component, either in object inspector or from code:
XDataServer1.SwaggerOptions.Enabled := True;
Alternatively, if you are using TXDataServerModule instead, you can just
use the unit XData.OpenAPI.Service
and call the method
RegisterOpenAPIService anywhere in your server application:
uses {...}, XData.OpenAPI.Service;
{...}
RegisterOpenAPIService;
OpenAPI document endpoint
Once OpenAPI document is enable, The OAS file is available through a GET request to the URL `/openapi/swagger.json`` relative to your server root URL. For example, if your server root is http://server:2001/tms/xdata/, then you will be able to access the file from this URL:
GET http://server:2001/tms/xdata/openapi/swagger.json
Swagger UI
XData server can optionally publish and endpoint to provide a SwaggerUI web-based interface that works as both a full documentation of your API as well a test interface. Swagger UI is a web-based front-end to dynamically document and test your API. Quoting their website:
"Swagger UI allows anyone - be it your development team or your end consumers - to visualize and interact with the API's resources without having any of the implementation logic in place. It's automatically generated from your Swagger specification, with the visual documentation making it easy for back end implementation and client side consumption."
Enabling Swagger UI
To enable SwaggerUI support in your server, just set the property SwaggerUIOptions.Enabled to true in your TXDataServer component, either in object inspector or from code:
XDataServer1.SwaggerUIOptions.Enabled := True;
Alternatively, if you are using TXDataServerModule instead, you can just
use the unit XData.SwaggerUI.Service
and call the method
RegisterSwaggerUIService
anywhere in your server application:
uses {...}, XData.SwaggerUI.Service;
{...}
RegisterSwaggerUIService;
Using SwaggerUI
Once enabled, SwaggerUI is available in the address /swaggerui
relative to your server base path. Just open your browser and go to the address:
http://server:2001/tms/xdata/swaggerui
It will display an interface like this:
Configuring SwaggerUI
The SwaggerUI interface can also be configured using the
SwaggerUIOptions
property of either
TXDataServer or
TXDataServerModule.
Available properties are:
Name | Description |
---|---|
ShowFilter | Boolean parameter. Default is False. When True, the SwaggerUI will display a filter edit box to search for API operations. |
DocExpansion | Enumerated parameter. Specifies the default expand level of the listed API operations. Valid values are: TSwaggerUIExpansion = (List, None, Full) Default value is List. |
TryOutEnabled | When True, SwaggerUI will already be in "try out" mode automatically. Default is false, which requires clicking the button "Try out" to test the endpoint. |
CustomParams | Allows adding custom parameters to the SwaggerUI JavaScript object. |
Examples:
XDataModule.SwaggerUIOptions.Filter := True;
XDataModule.SwaggerUIOptions.DocExpansion := TSwaggerUIExpansion.None;
Redoc
XData server can also publish and endpoint to provide a Redoc web-based interface. Redoc is an open source tool for generating documentation from OpenAPI (formerly Swagger) definitions.
You can use it to provide to your users a nice documentation about your API.
Enabling Redoc
To enable Redoc support in your server, just set the property
RedocOptions.Enabled
to true in your TXDataServer
component, either in object inspector or from code:
XDataServer1.RedocOptions.Enabled := True;
Alternatively, if you are using TXDataServerModule
instead, you can just
use the unit XData.Redoc.Service
and call the method
RegisterRedocService
anywhere in your server application:
uses {...}, XData.Redoc.Service;
{...}
RegisterRedocService;
Using Redoc
Once enabled, Redoc will be available from the address /redoc
relative to your server base path. Just open your browser and go to the address:
http://server:2001/tms/xdata/redoc
It will display an interface like this:
Configuring Redoc
The Redoc interface can also be configured using the RedocOptions
property of either
TXDataServer or
TXDataServerModule.
You can use CustomParams
property to set any Redoc parameter and its value.
You can refer to Redoc documentation for the full list of parameters.
For example:
XDataServer1.RedocOptions.CustomParams.Values['disable-search'] := 'true';
Customizing the OpenAPI document
There are plenty of ways to improve the OpenAPI document generated by XData. You can use XML documentation to add descriptions and content, make use of validation attributes, exclude methods, and so on.
Customizing document header and description
XData also takes the model name, version and description into account to build the final document. You can configure such settings directly by changing some properties of the XData model (remember that XDataServer in this example is a TXDataServer component):
XDataServer.Model.Title := 'Mathematics API';
XDataServer.Model.Version := '1.0';
XDataServer.Model.Description :=
'### Overview'#13#10 +
'This is an API for **mathematical** operations. '#13#10 +
'Feel free to browse and execute several operations like *arithmetic* ' +
'and *trigonometric* functions'#13#10#13#10 +
'### More info'#13#10 +
'Build with [TMS XData](https://www.tmssoftware.com/site/xdata.asp), from ' +
'[TMS Software](https://www.tmssoftware.com).' +
'A Delphi framework for building REST servers'#13#10 +
'[]' +
'(https://www.tmssoftware.com)';
Note that you can use Markdown syntax to format the final text. Here is what it will look like:
Excluding methods
You can flag some service contract
methods to be excluded from the OpenAPI document, by simply adding the
\[SwaggerExclude\]
attribute to the method:
[ServiceContract]
[Route('arith')]
IArithmeticService = interface(IInvokable)
['{9E343ABD-D97C-4411-86BF-AD2E13BE71F3}']
[HttpGet] function Add(A, B: Double): Double;
[HttpGet] function Subtract(A, B: Double): Double;
[SwaggerExclude]
[HttpGet] function NotThisFunctionPlease: Integer;
end;
In the example above, methods Add
and Subtract
will be added to the documentation, but method NotThisFunctionPlease
will not appear.
SwaggerOptions property
For the OpenAPI document specification, you can use SwaggerOptions property of either TXDataServer or TXDataServerModule to configure the specification returned by the server:
XDataModule.SwaggerOptions.AuthMode := TSwaggerAuthMode.Jwt;
For AuthMode
property, options are TSwaggerAuthMode.Jwt
or None
. When Jwt is enabled, a new security definition named jwt
requiring an Authorization header will be added to all requests.
You can also configure the specification by passing parameters in the query part of the URL, and they can be one of the following:
Name | Description |
---|---|
ExcludeEntities | Boolean parameter. Default is False. When True, the specification will not contain the automatic CRUD operations on entities provided automatically by XData (entity resources). Example: /openapi/swagger.json?ExcludeEntities=True |
ExcludeOperations | Boolean parameter. Default is False. When True, the specification will not contain any service operations. Example: /openapi/swagger.json?ExcludeOperations=True |
AuthMode | String parameter. Options are "none" and "jwt". When jwt is specified, a new security definition named jwt requiring an Authorization header will be added to all requests. Example: /openapi/swagger.json?authmode=jwt |
Automatic validation rules
If you use some validation attributes in your classes, like Range
, MinLength
or MaxLength
, such rules are automatically included in the OpenAPI document. For example, suppose you have a DTO class declared like this and used as an input for and endpoint (other properties removed for clarity):
[Entity, Automapping]
TTrack = class
strict private
[Required, MaxLength(150)]
FName: string;
[Range(0, 4800000)]
FMilliseconds: Nullable<integer>;
The OpenAPI document will include the properties with maxLength
and minimum
/maximum
properties:
"MusicEntities.TTrack": {
"properties": {
"Name": {
"type": "string",
"maxLength": 150,
"x-data-type": "String",
"x-length": 255
},
"Milliseconds": {
"type": "integer",
"maximum": 4800000,
"minimum": 0,
"x-data-type": "Int32"
}
}
Such information will of course be used by the OpenAPI tools you might use. For example, the final Redoc documentation will nicely show the restrictions of such properties:
Using XML Documentation
A good (if not the best) way to document your source code is to use XML Documentation Comments. In the interfaces and methods that build your service contract, you can simply add specific XML tags and content, like this:
/// <summary>
/// Retrieves the sine (sin) of an angle
/// </summary>
/// <remarks>
/// Returns the Sine (Sin) value of an angle radians value.
/// The value returned will be between -1 and 1.
/// If the angle is zero, the returned value will be zero.
/// </remarks>
/// <param name="Angle">
/// The angle in radians.
/// </param>
function Sin(Angle: Double): Double;
And Delphi IDE will automatically use it for Help Insight, showing you information about the method on-the-fly. For example, if some developer is trying to use the Sin method of your API, information will be conveniently displayed:
The good news is that, with XData, you can use such XML comments in the OpenAPI documnt that is generated automatically by XData, improving even more your REST API documentation. Since the API endpoints are generated directly from the interfaced and methods, XData knows exactly the meaning of each documentation and can map it accordingly to Swagger.
Enabling generation of XML documentation files
XData needs to read the XML files with the comments to import it into the Swagger document. You need to tell Delphi compiler to generate the XML documentation files.
In your project options (Delphi menu Project | Options, or Shift+Ctrl+F11), go to "Building, Delphi Compiler, Compiling" (for Delphi 10.4.1 Sydney. Previous Delphi version might differ), then enable option "Generate XML documentation". You might also want to explicitly set the directory where the XML files will be generated, in option "XML documentation output directory". It's recommended to use ".\$(Platform)\$(Config)", this way the XML files will be in the same folder as the executable.
Importing XML documentation in Swagger
XML documentation usage in Swagger can be enabled with a single line of code:
uses {...}, XData.Aurelius.ModelBuilder;
...
TXDataModelBuilder.LoadXmlDoc(XDataServer.Model);
Add the line at the beginning of your application, be it in your dpr file, or initialization section of some unit, or in the OnCreate event of your TDataModule that contains your XData/Sparkle components. In the first parameter you must provide the XData model you want to import XML files to. In the example above, XDataServer is a TXDataServer component. If you are using multi-model design, just provide the proper model there.
LoadXmlDoc will try to find the XML files in the same directory as your application is located. If the XML files are in a different folder, you can specify it explicitly using a second parameter:
TXDataModelBuilder.LoadXmlDoc(XDataServer.Model, 'C:\MyXMLFiles');
Once you do that, if you check your Swagger documentation via Swagger-UI, you will see something like this:
Note how the content of summary tag goes directly at the right of the GET button, as a summary for the endpoint.
The content of remarks tag is the detailed description of the endpoint.
And the content of each param tag explains each respective parameter. Sweet!
Using different documentation for Help Insight and Swagger
Reusing the same XML comments is nice as you don't repeat yourself. Document your code just once, and the same documentation is used for documenting your Delphi interfaces (Delphi developments) and your REST API (API consumer development).
But, if for some reason you want to use different documentation content for Delphi developers and for REST API users, that's also possible. You can use the specific swagger tag to fill specific parts of the documentation. You then use the name attribute to differentiate between swagger tags.
For example, suppose the following documentation:
Note that tags summary (1) and param (2 and 3) are the regular XML documentation tags. They will be used for Help Insight:
And swagger tags with no name attribute (A), or name param-A (B), param-B (C) and remarks (D) will be used exclusively for Swagger documentation:
Customizing tags
You can also customize the tags in Swagger. Endpoints are grouped together inside a tag, which can have a name and description.
By default, the name of the tag will be path segment of the interface service. But you can change it using swagger tag with tag-name attribute.
The description of the tag by default is empty, but you can define it using the regular summary tag, or optionally using the swagger tag with tag-description attribute.
Consider the following documentation for both IArithmenticService and ITrigonometryService:
The above tags will generate the following output in Swagger UI:
Using tag groups
If you are using Redoc, it also supports the concept of tag groups.
It's an even higher level than tags, where you can group tags under a common name. To "put" a tag in a specific tag group use the swagger
XML tag with the tag-group
attribute:
/// <swagger name="tag-group">Customers</swagger>
/// <swagger name="tag-name">Customer Authentication</swagger>
/// <swagger name="tag-description">Endpoints for authenticating customers</swagger>
ICustomerAuthenticationService = interface(IInvokable)
Endpoints declared in the above interface will be under tag "Customer Authentication", which in turn will be under tag group "Customers":
Note
When you use tag groups in Redoc, a tag that is not in a group is not displayed at all. You must add every tag to at least one group.
To avoid having to flag all endpoints in tag groups, you can set SwaggerOptions.DefaultTagGroup
property to a non-empty value. This will make all tags without a tag group to get listed under that group name:
XDataServer1.SwaggerOptions.DefaultTagGroup := 'Other';
Flagging properties as required
To set a specific property as required in Swagger documentation, regardless how it's defined in the XData model, just add an XML comment with the swagger
tag and required
attribute to the mapped class member:
/// <swagger name="required" />
FSomeRequiredProperty: Integer;
Flagging endpoints as deprecated
To show an endpoint as deprecated in Swagger documentation, add a XML comment with swagger
tag and deprecated
attribute to the method corresponding to the endpoint:
/// <swagger name="deprecated" />
function Sum(A, B: double): double;