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. WifeAsleep's avatar WifeAsleep says:

    After looking into a few of the blog articles on your website, I truly appreciate your technique of writing a blog. I bookmarked it to my bookmark site list and will be checking back in the near future. Please check out my web site as well and let me know how you feel.

  2. คอนเทนต์นี้ อ่านแล้วเข้าใจง่าย ครับ
    ผม เพิ่งเจอข้อมูลเกี่ยวกับ เรื่องที่เกี่ยวข้อง
    ดูต่อได้ที่ เว็บสล็อต
    สำหรับใครกำลังหาเนื้อหาแบบนี้
    เพราะให้ข้อมูลเชิงลึก
    ขอบคุณที่แชร์ บทความคุณภาพ นี้
    และอยากเห็นบทความดีๆ แบบนี้อีก

  3. MarioNet's avatar MarioNet says:

    Умение стильно одеваться играет важную роль в создании первого впечатления.
    Она помогает передать настроение и выглядеть гармонично.
    Грамотно подобранный образ влияет на то, как человека воспринимают окружающие.
    В повседневной жизни одежда может добавлять уверенности.
    https://fashionessa.ru/style/2024-06-20-viktor-vembanyama-poyavilsya-na-pokaze-louis-vuitton-v-parizhe/
    Продуманный гардероб облегчает общение.
    При этом важно учитывать индивидуальные особенности и уместность ситуации.
    Стиль дают возможность обновлять образ.
    В итоге, умение стильно одеваться помогает чувствовать себя уверенно.

  4. 888neo's avatar 888neo says:

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

  5. some studies have found a reduced risk for acne among people consuming

    References:
    http://hybrid-forum.ru/profile.php?id=1706

  6. Casino_dxpt's avatar Casino_dxpt says:

    Здесь доступны как классические игровые автоматы, так и современные видеослоты.
    Пинко Казино
    Сайт адаптирован для мобильных устройств и ПК.

  7. Andy's avatar Andy says:

    I’m really loving the theme/design of your blog. Do you ever run into any web browser compatibility problems? A couple of my blog audience have complained about my blog not working correctly in Explorer but looks great in Safari. Do you have any tips to help fix this issue?

    my page: http://www.xn--2s2b270b.com/bbs/board.php?bo_table=free&wr_id=555079

  8. anabolic steroids are suspected to be toxic to the liver

    References:
    http://www.p2sky.com/home.php?mod=space&uid=6232438&do=profile

  9. GichardAmomi's avatar GichardAmomi says:

    The other day, while I was at work, my cousin stole my iPad and tested to see if it can survive a thirty foot drop, just so she can be a youtube sensation. My iPad is now destroyed and she has 83 views. I know this is entirely off topic but I had to share it with someone!
    buy viagra sexual porno xxx adults pills

  10. WifeAsleep's avatar WifeAsleep says:

    Hello my friend! I wish to say that this article is awesome, great written and include almost all important infos. I would like to see extra posts like this .

  11. xxx's avatar xxx says:

    An interesting discussion is definitely worth comment. I think
    that you ought to write more about this topic, it might not be a taboo matter but typically people do not discuss such topics.

    To the next! Kind regards!!

  12. Great blog post. Appreciate the effort put into this. The info about streaming infrastructure cleared things up for me. Going to bookmark this.

    I have been curious about how streaming works for a project and this article is one of the better ones I found. Thanks.

    Ran into this while searching for streaming tech. Glad I did. What you mentioned about load times rings true.

    Really helpful article about video platforms. People generally never consider the tech.

  13. Heya! I understand this is somewhat off-topic but I needed
    to ask. Does managing a well-established blog like yours require a massive amount work?
    I am completely new to operating a blog but I do write in my diary everyday.
    I’d like to start a blog so I can easily share my personal
    experience and thoughts online. Please let me know
    if you have any recommendations or tips for new aspiring blog owners.

    Appreciate it!

  14. m4autobet's avatar m4autobet says:

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

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

  15. g2g59's avatar g2g59 says:

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

  16. Great addition to the series. I’ve found that taking the time to write good Swagger comments not only helps others understand my API, but it often clarifies the design for me as well. It’s a step that’s easy to skip, but you’ve made a strong case for why it’s worth the effort.

  17. Malcolmmomma's avatar Malcolmmomma says:

    Real-money gaming platforms have become immensely widespread due to their unmatched convenience.
    Users can access their preferred games at any time and from anywhere with an internet connection.
    The excitement of playing for actual money adds an extra layer of engagement.
    A massive selection of options appeals to all taste and budget.
    Bonuses and loyalty programs offer added incentives to retain participants engaged.
    Today’s sites guarantee safe transactions and fair gaming experiences.
    ice fishing

  18. highroi – Mobile version looks perfect; no glitches, fast scrolling, crisp text.

  19. Jeffry's avatar Jeffry says:

    โพสต์นี้ มีประโยชน์มาก ค่ะ
    ดิฉัน ได้อ่านบทความที่เกี่ยวข้องกับ เรื่องที่เกี่ยวข้อง

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

  20. ScottGob's avatar ScottGob says:

    Современная ортодонтия для взрослых, кликните сюда <a href=
    https://rentry.co/bkxev33q

  21. Frederic's avatar Frederic says:

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

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

  23. Great addition to the series. I’ve found that taking the time to write thorough Swagger comments not only generates better documentation but actually improves my own understanding of the API’s intended behavior. It forces you to think through edge cases. Looking forward to the next part.

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

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

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

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

  28. Сайты для взрослых существуют как специализированные платформы с возрастными рамками.
    Их главная цель — гарантировать просмотр к контенту, адресованному только совершеннолетней аудитории.
    Эти ресурсы дают возможность создателям публиковать произведения, не предназначенные для детей.
    Подобные сервисы выполняют и просветительскую роль в области отношений.
    Владельцы таких проектов обязаны выполнять правовые требования о распространении чувствительного материала.
    Помимо прочего, данные порталы нередко используют специальные меры проверки возраста.
    Таким образом, наличие таких площадок — это ответ на естественный спрос конкретной аудитории.
    порно видео

  29. Leonard Pelc's avatar Leonard Pelc says:

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

  30. viralshift – Mobile version looks perfect; no glitches, fast scrolling, crisp text.

  31. Great addition to the series. I’ve found that taking the time to write thorough Swagger comments not only helps others understand my API, but it forces me to think more clearly about my own design. It’s an underrated step in the development process.

Comments are closed.