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. เนื้อหานี้
    น่าสนใจดี ค่ะ

    ผม ไปอ่านเพิ่มเติมเกี่ยวกับ บีเอฟคลับ
    ดูต่อได้ที่ เว็บไซต์ bfclub

    ลองแวะไปดู
    เพราะอธิบายไว้ละเอียด

    ขอบคุณที่แชร์ เนื้อหาดีๆ
    และหวังว่าจะได้เห็นโพสต์แบบนี้อีก

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

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

  4. strategystore – Overall, professional vibe here; trustworthy, polished, and pleasantly minimal throughout.

  5. Davidten's avatar Davidten says:

    stromectol reviews ivermectin generic cream stromectol reviews

  6. Eugenia's avatar Eugenia says:

    เนื้อหานี้ ให้ข้อมูลดี ครับ
    ดิฉัน ได้อ่านบทความที่เกี่ยวข้องกับ เนื้อหาในแนวเดียวกัน
    ซึ่งอยู่ที่ Eugenia
    ลองแวะไปดู
    มีตัวอย่างประกอบชัดเจน
    ขอบคุณที่แชร์ เนื้อหาดีๆ นี้
    และอยากเห็นบทความดีๆ แบบนี้อีก

  7. Annetta Kell's avatar Annetta Kell says:

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

  8. Daysi Lavi's avatar Daysi Lavi says:

    keywordvault – Found practical insights today; sharing this article with colleagues later.

  9. Nick Mattock's avatar Nick Mattock says:

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

  10. Monty Parks's avatar Monty Parks says:

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

  11. Модель Audemars Piguet Royal Oak известны своим уникальным дизайном.
    Эту октагональный безель с видимыми винтами является подлинной легендой в часовом мире.
    Данная серия была выпущена в далёком 1972-м как первые роскошные спортивные часы из нержавеющей стали.
    Эта смелая концепция тогда совершила громкий переворот в часовой индустрии.
    купить часы Royal Oak Audemars Piguet
    Кроме внешности, часы ценятся за высочайшее исполнение обработки и механизма.
    Общеизвестно, что любой экземпляр собирается вручную квалифицированными мастерами.
    Сегодня Royal Oak остаются символом престижа и тонкого вкуса.
    Именно так они востребованы как среди коллекционеров, так и у поклонников роскоши.

  12. keywordking – Navigation felt smooth, found everything quickly without any confusing steps.

  13. Michell's avatar Michell says:

    เนื้อหานี้ น่าสนใจดี ครับ
    ดิฉัน เพิ่งเจอข้อมูลเกี่ยวกับ หัวข้อที่คล้ายกัน
    สามารถอ่านได้ที่ Michell
    น่าจะถูกใจใครหลายคน

    เพราะให้ข้อมูลเชิงลึก
    ขอบคุณที่แชร์ บทความคุณภาพ นี้
    และหวังว่าจะมีข้อมูลใหม่ๆ มาแบ่งปันอีก

  14. Chi Burkin's avatar Chi Burkin says:

    rankgenius – Color palette felt calming, nothing distracting, just focused, thoughtful design.

  15. seomastery – Navigation felt smooth, found everything quickly without any confusing steps.

  16. trafficwizard – Found practical insights today; sharing this article with colleagues later.

  17. Roccoiterb's avatar Roccoiterb says:

    The flavor options for the sake of these CBD gummies and https://www.nothingbuthemp.net/collections/mushroom-gummies are impressive. Each gather tastes logical quite than disproportionately phony, and the feel is pleasantly chewy. The jug seals pantihose, which keeps them fresh and easy to store fitting for longer periods.

  18. webstrategy – Loved the layout today; clean, simple, and genuinely user-friendly overall.

  19. Toniscrive's avatar Toniscrive says:

    Hi! Do you know if they make any plugins to assist with Search Engine Optimization? I’m trying to get my blog to rank for some targeted keywords but I’m not seeing very good success. If you know of any please share. Many thanks!
    https://share.google/EYkVFooksGoGFcD7x

  20. Hyman Colas's avatar Hyman Colas says:

    TOP 10 BEST – Navigation felt smooth, found everything quickly without any confusing steps.

  21. Ranee Clough's avatar Ranee Clough says:

    brandengine – Color palette felt calming, nothing distracting, just focused, thoughtful design.

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

  23. Kelley Oya's avatar Kelley Oya says:

    conversionpro – Found practical insights today; sharing this article with colleagues later.

  24. Rogergab's avatar Rogergab says:

    This CBD lubricator and best Delta 9 Beer stands out because of its cagey flatten texture and balanced taste. The bottle forge is fawning and applicable, and the dropper works strictly without dripping. It feels like a well-crafted merchandise мейд with prominence to detail, from labeling to packaging.

  25. Mikel Tangen's avatar Mikel Tangen says:

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

  26. serpmaster – Navigation felt smooth, found everything quickly without any confusing steps.

  27. trafficpilot – Overall, professional vibe here; trustworthy, polished, and pleasantly minimal throughout.

  28. rankmachines – Color palette felt calming, nothing distracting, just focused, thoughtful design.

  29. This online square face generator is the best Picrew alternative in English — create adorable square face icons for social media and game development

  30. ข้อมูลชุดนี้ น่าสนใจดี ค่ะ
    ดิฉัน ได้อ่านบทความที่เกี่ยวข้องกับ เนื้อหาในแนวเดียวกัน
    สามารถอ่านได้ที่ megaways pantip
    ลองแวะไปดู
    มีตัวอย่างประกอบชัดเจน
    ขอบคุณที่แชร์ บทความคุณภาพ นี้
    และหวังว่าจะได้เห็นโพสต์แนวนี้อีก

  31. trafficpilot – Mobile version looks perfect; no glitches, fast scrolling, crisp text.

  32. Tiny Shamir's avatar Tiny Shamir says:

    seoworks – Navigation felt smooth, found everything quickly without any confusing steps.

  33. Ivana Merwin's avatar Ivana Merwin says:

    trafficforge – Navigation felt smooth, found everything quickly without any confusing steps.

  34. rankmachines – Loved the layout today; clean, simple, and genuinely user-friendly overall.

  35. ThomasWidly's avatar ThomasWidly says:

    Сейчас кроссовки завоевали огромную известность везде.
    Такую обувь выбирают люди всевозможных возрастов и профессий.
    Основная причина столь высокой любви — удобство и универсальность.
    https://hypebeasts.ru/
    Известные марки постоянно представляют новые линейки, подогревая ажиотаж.
    Сникерсы прочно закрепились в уличную моду и повседневность.
    С каждым сезоном их востребованность лишь увеличивается.

  36. website's avatar website says:

    Appreciate the recommendation. Will try it out.

  37. Kennethadder's avatar Kennethadder says:

    mexico pharmacy: AccessBridge – AccessBridge Pharmacy

  38. References:

    Online-https://graph.org/Best-Australian-Online-Casino-2026-Ranked-04-20-bonuses

  39. Abe Dworak's avatar Abe Dworak says:

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

  40. Sharyl Brodi's avatar Sharyl Brodi says:

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

Comments are closed.