API Part 7 – Swagger Comments

In the previous post, I introduced Swagger and showed how to set up your project for Swagger. In this post I will show how to add Swagger comments to annotate your program.

In earlier posts we looked at the database of cars and the Get method that retrieves the entire list. That can be quite a lot of data going over the wire. What we want instead is to send pages. I’ll show that briefly and then we’ll annotate that code.

In the CarController we’ll have a Get method that takes three parameters: showDeleted, pageNumber and pageSize. The first we’ve seen before, it determines whether the list returned to the caller will include our deleted records. The second, pageNumber, will designate which page of data we want to return (zero based). The third parameter, pageSize, will designate how many records to return per page.

Thus, if we were to write

Get(false,3,4)

we would expect to get back records 17, 18, 19 and 20, because page 0 would have records 1-4, page 1 would have 5-8, etc.

Here is the compete endpoint that will directly call our repository (we won’t bother with a service for this example).

public async Task<IEnumerable<Car>> Get([FromRoute] bool showDeleted, int pageNumber, int pageSize )
{
    return await _carRepository.Get(showDeleted, pageNumber, pageSize);
}

When the repository is called, the parameters are passed in, and it does its magic. For now, however, we are only concerned with documenting this method. We do that with XML comments, designated by three forward slash marks (///).

First, we will document the purpose of the endpoint; that is, what it does. We do that in the summary

/// <summary>
/// Get all the cars in the Database 
/// </summary>

Next, we want to document the parameters

/// <param name="returnDeletedRecords">If true, the method will return all the records,
/// including the ones that have been deleted</param>
/// <param name="pageOffset">which page to display</param>
/// <param name="pageSize">how many records to display per page</param>

Finally, I’m going to document the possible response codes. Note, these are, by no means, all that you can document, but they’ll give us a good idea of how it is done

/// <response code="200">Cars returned</response>
/// <response code="404">Specified Car not found</response>
/// <response code="500">An Internal Server Error prevented the request from being executed.</response>

When an error is encountered and we return one of these codes, the text we’ve specified goes along for the ride, which is enormously helpful to the calling client.

At the top of the swagger page is our summary

At each parameter is our designated text

Finally, each of the error codes is documented

It is a best practice to document all of the endpoints. Many developers go further, and document all of the methods in both the service and the repository; that is a decision to be made by the team. Since the endpoint is the only thing visible to the client, it has the greatest claim on your time and effort. Remember, “comments rust,” and that is as true for Swagger comments as any other.

Unknown's avatar

About Jesse Liberty

** Note ** Jesse is currently looking for a new position. You can learn more about him at https://jesseliberty.bio Thank you. Jesse Liberty has three decades of experience writing and delivering software projects and is the author of 2 dozen books and a couple dozen online courses. His latest book, Building APIs with .NET, is now available wherever you buy your books. Liberty was a Team Lead and Senior Software Engineer for various corporations, a Senior Technical Evangelist for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS. He is a 13 year Microsoft MVP.
This entry was posted in API, C#, Essentials and tagged . Bookmark the permalink.

2,572 Responses to API Part 7 – Swagger Comments

  1. Minh Halle's avatar Minh Halle says:

    funnelbot – Appreciate the typography choices; comfortable spacing improved my reading experience.

  2. Randal Holt's avatar Randal Holt says:

    seoaccelerator – Pages loaded fast, images appeared sharp, and formatting stayed consistent.

  3. sa影视's avatar sa影视 says:

    热播剧集,万众期待的年度爆款影视作品。恶之华国语版

  4. Image to Image AI provides a simple drag-and-drop interface that lets anyone generate high-resolution, AI-enhanced images in seconds.

  5. AI Image Editor is a powerful AI image editor for restoring and enhancing images.

  6. HEIC to JPG's avatar HEIC to JPG says:

    HEIC to JPG offers a simple, fast, and free way to convert your HEIC files to high-quality JPG images online.

  7. Ai Photo Enhancer is a fast and easy AI-powered photo enhancement tool.

  8. Concrete Calculator is a free online tool that helps you quickly estimate concrete volume for slabs, footings, and foundations.

  9. Quem evitou chase de perda preservou melhor o saldo.

  10. Brat Generator Online makes it easy to create brat-style text visuals instantly.

  11. With Restore Old Photos, you can easily repair damaged, faded, or torn photographs and preserve them for future generations

  12. marketsprint – Appreciate the typography choices; comfortable spacing improved my reading experience.

  13. rankhustle – Appreciate the typography choices; comfortable spacing improved my reading experience.

  14. Mac Reekers's avatar Mac Reekers says:

    digitalpush – Content reads clearly, helpful examples made concepts easy to grasp.

  15. seocommand – Mobile version looks perfect; no glitches, fast scrolling, crisp text.

  16. betflix365's avatar betflix365 says:

    ข้อมูลชุดนี้ น่าสนใจดี ค่ะ
    ผม ไปเจอรายละเอียดของ เนื้อหาในแนวเดียวกัน
    ที่คุณสามารถดูได้ที่ betflix365
    เผื่อใครสนใจ
    มีตัวอย่างประกอบชัดเจน
    ขอบคุณที่แชร์ ข้อมูลที่มีประโยชน์ นี้
    จะรอติดตามเนื้อหาใหม่ๆ ต่อไป

  17. seo_tzPr's avatar seo_tzPr says:

    Как продвижение сайта в поисковых системах меняется после апдейтов алгоритмов?

  18. seo_pvKn's avatar seo_pvKn says:

    комплексное seo продвижение сайта https://raskrutka-sajtov-zakazat.ru/ .

  19. rankhustle – Overall, professional vibe here; trustworthy, polished, and pleasantly minimal throughout.

  20. Hisako Ocker's avatar Hisako Ocker says:

    funnelpro – Appreciate the typography choices; comfortable spacing improved my reading experience.

  21. Vince Hoge's avatar Vince Hoge says:

    brandclicks – Appreciate the typography choices; comfortable spacing improved my reading experience.

  22. Nubia Fest's avatar Nubia Fest says:

    growthhive – Appreciate the typography choices; comfortable spacing improved my reading experience.

  23. trafficnest – Pages loaded fast, images appeared sharp, and formatting stayed consistent.

  24. капсульный дом челябинск купить капсульный дом челябинск купить .

  25. Yuki Cradle's avatar Yuki Cradle says:

    brandclicks – Bookmarked this immediately, planning to revisit for updates and inspiration.

  26. Sel_fyKl's avatar Sel_fyKl says:

    Напишу пару абзацев — попробовал казино Selector недавно. Зашёл по рекомендации казино Selector. Стартовое предложение щедрое, но вейджер читайте до того как жать «активировать».
    Минимальный депозит 100 ? по правилам кассы, вывод от 500 ? — лимиты адекватные.
    Демо на многих слотах без регистрации — удобно потестить.
    Вывод: у меня уложилось в сутки, иногда быстрее.
    Зеркало Selector Casino беру из рассылки или чата поддержки.
    Мобильная версия в браузере норм, приложение ставил с официального раздела — пуши на выплаты удобны.
    Кто в Selector — как вам отыгрыш и поддержка?

  27. Alt_veKl's avatar Alt_veKl says:

    Коллеги — сравнивал пару казино на днях и подсказали alteja-kpk.ru/. Промокод CACTUS2026PLAY ввёл при регистрации — до 200% на первый депозит и 230 фриспинов по правилам акции.
    Форма лаконичная, без лишних полей — оценил.
    Касса: карты, СБП, электронные сервисы, USDT — выбрал что удобнее.
    Pragmatic Play, Evolution, NetEnt, Play’n GO, BGaming, Amatic — провайдеры привычные.
    Зеркало Кактус казино нужно когда основной домен «плавает».
    SSL на месте, лицензия Curacao в подвале — сверяю перед входом.
    Кто уже в Cactus Casino — как вам кэшбэк и еженедельные акции?

  28. sa影视's avatar sa影视 says:

    不得不说追风者剧场版质感真的很棒,角色刻画入木三分极具感染力,这种教科书级别的表现令人叹服高清免费点击观看

  29. アダルトコンテンツは 人間の性について 理解するための 一つの手段になり得る。
    限定的な 環境(研究目的)において、それらは 身体の仕組みの 理解を 助けることがある。
    コンプライアンスを 守った上で、同意や 安全な行動の 実例を 示すことも可能だ。
    児童ポルノ
    研究者による 監督下の 使用は、誤解を 減らし、現実的な 認識を 促進する。
    無論、これらは 無作為な 利用ではなく、科学的な 学習プログラムの 一部として 扱われるべきだ。

  30. ShanepiliA's avatar ShanepiliA says:

    Thank you for the good writeup. It if truth be told was once a amusement account it. Glance complex to more introduced agreeable from you! However, how can we communicate?
    https://share.google/DaO9m2QCkUzgWJpfp

  31. *%LowPrice&HighQuality-Guestpost【dr50+real-traffic】Telegram @buycasinolink

  32. Greetings! I know this is kinda off topic but I was wondering
    if you knew where I could find a captcha plugin for my comment form?
    I’m using the same blog platform as yours and I’m having problems finding one?
    Thanks a lot!

Comments are closed.