Что нового
  • Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

Documenting your Delphi REST API the easy way

Sascha

Заместитель Администратора
Команда форума
Администратор
Регистрация
9 Май 2015
Сообщения
1,071
Баллы
155
Возраст
51
Create documentation is boring. At least that's my opinion, and most developers I know also don't like to write it. But that's something we need to do, of course. Thus, the easiest it gets to document things, the better.


Photo by

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

on

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.



With TMS XData, you create your REST API server using Delphi very easily, but you also get it documented almost automatically using the automatic Swagger generation feature. Since all endpoints are strong typed in server, all it takes is just to enable a single property and have your endpoints listed and testable.

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.



But now XData takes it to another level. A good (if not the best) way to document your source code is to use

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

. 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

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

, 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:


xdata-xml-help-insight



The good news is that, with XData, you can use such XML comments in the

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

that are 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.

By asking Delphi to generate the XML documentation files, and using a single line of code like this:


uses {...}, XData.Aurelius.ModelBuilder;
...
TXDataModelBuilder.LoadXmlDoc(XDataServer.Model);


XData will reuse the documentation and include it in Swagger:

xdata-xml-help-insight



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. For example, suppose the following documentation:




Note that tags summary and param are the regular XML documentation tags. They will be used for Help Insight:

xdata-xml-help-insight-2



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:

xdata-xml-swagger-example-2



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 either swagger tag using 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 :

xdata-xml-tag-source



The above tags will generate the following output in Swagger UI:

xdata-xml-swagger-tags




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

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

:

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 +
'[![TMS Software](https://download.tmssoftware.com/business/tms-logo-small.png)](https://www.tmssoftware.com)';


Note that you can use

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

syntax to format the final text. Here is what it will look like:

xdata-swagger-doc-description



You can read more about using XML documentation in Swagger with TMS XData by

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

.


Finally, this video shows in details how REST/JSON documentation works with XData, explaining how Swagger and Help Insight documentation is built from single source, how XML comments can be used, and even more. Lots of useful information there!


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх