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

    The THC Liquid arrived highly protected, with secure wrapping and indisputable instructions included. The whole shooting match was organized neatly advantageous the chest, which мейд the unboxing experience satisfactory and polished.

  2. Didn’t expect to find something this useful today. Well done. I also check catch bugs codes here when I need a quick reference.

  3. Have you noticed any differences depending on the situation? I’m curious whether what you described holds true across the board. I also check universal tower defense x codes here when I need a quick reference.

  4. Helpful read. I also check Noob Tower Defense for Roblox tower defense codes and guide notes. I also check noob tower defense tier list here when I need a quick reference.

  5. Helpful read. I also check Survive Zombie Arena for zombie survival game codes and guide notes. I also check survive zombie arena tier list here when I need a quick reference.

  6. Thanks for sharing this. SailorPiece covers Roblox anime-game codes and guide notes in a way that is easy to scan. I also check sailor piece codes here when I need a quick reference.

  7. DavidFraSe's avatar DavidFraSe says:

    Buy Viagra online cheap best price for viagra 100mg – Buy Viagra online cheap

  8. sailor piece's avatar sailor piece says:

    Clear post. SailorPiece is useful when I need Roblox code checks and update timing in one place. I also check sailor piece here when I need a quick reference.

  9. Arisha43sr's avatar Arisha43sr says:

    Hello !
    Hello. A 43 great website 1 that I found on the Internet.
    Check out this website. There’s a great article there. https://listinside.com/what-is-the-asian-1×2-handicap-a-collection-of-great-tips-for-beginners/|

    There is sure to be a lot of useful and interesting information for you here.
    You’ll find everything you need and more. Feel free to follow the link below.

  10. Great breakdown of Swagger comments for API documentation! I have been looking into similar AI-powered tools to speed up figure creation. FigureGPT has been surprisingly helpful for generating scientific diagrams automatically.

  11. This article provided exactly what I was looking for. Thank you for the great insight!

  12. LewisGor's avatar LewisGor says:

    Hi, yup this paragraph is genuinely fastidious and I have learned lot of things from it on the topic of blogging. thanks.
    บาคาร่า

  13. Great breakdown of how Swagger comments can streamline API documentation. I’ve found that adding clear summaries and response examples really helps my team avoid confusion during integration. Do you have any tips for keeping comments concise without losing critical details for complex endpoints?

  14. Great explanation and very informative. You can tell a lot of effort went into this.

  15. Williammor's avatar Williammor says:

    Casa eficiente – Wood frame, Casa eficiente

  16. JeromeRof's avatar JeromeRof says:

    The THC superficial cream, https://tribetokes.com/cbd-pain-creams/ , and THCA pen all have a well-made and peaceful to use. The cream has a smooth consistency and absorbs nicely without impression greasy. The THCA blossom has a raw character and even advent, while the vape pen is spartan, convenient, and smooth. Inclusive, the products handle steadfast, thoughtfully packaged, and becoming recompense a relaxed critical routine.

  17. deltakernel – Mobile version looks perfect; no glitches, fast scrolling, crisp text.

  18. Brazilian players Google “cassino confiável 2026” before depositing now.

  19. XRumerTest's avatar XRumerTest says:

    Hello. And Bye.

  20. ChrisTok's avatar ChrisTok says:

    ivermectin lotion ivermectin drug buy ivermectin for humans uk

  21. Arisha43sr's avatar Arisha43sr says:

    Hello guys
    Hello. A 43 cool site 1 that I found on the Internet.
    Check out this site. There’s a great article there. https://bizomag.com/the-secrets-of-casino-software-an-in-depth-guide-to-understanding-online-gambling-software/|

    There is sure to be a lot of useful and interesting information for you here.
    You’ll find everything you need and more. Feel free to follow the link below.

  22. Craiggairm's avatar Craiggairm says:

    The field of THCA floret lies in a thc-a flower process called decarboxylation. In its untested situation, THCA is non-psychoactive because its molecular system has an extra carboxyl ring. Applying stimulation removes this ring, transforming it into effectual THC. It’s a fascinating shred of chemistry that turns new, compliant hemp buds into a definitive, strong sensory endure for good occasionally you luminosity it up.

  23. betflik's avatar betflik says:

    You actually revealed that very well! https://medibang.com/author/28180807/

  24. betflix's avatar betflix says:

    Excellent items from you, man. I have consider
    your stuff prior to and you’re simply extremely great.
    I really like what you’ve bought here, really like what you’re
    saying and the best way wherein you are saying it.
    You make it enjoyable and you continue to take care of to keep
    it wise. I can not wait to learn far more from you. That is actually a tremendous web site.
    betflix

  25. BrandonHoomb's avatar BrandonHoomb says:

    Правильный подбор офисной мебели непосредственно влияет на самочувствие и продуктивность сотрудников.
    Важнейший фактор — это удобство cтульев и столов.
    Добротная корпусная мебель может снижать усталость и профилактировать заболевания позвоночника.
    Точно так же важен внешний вид предметов, ведь он создаёт образ компании для клиентов и посетителей.
    https://b2.chenews.ru/redirect.php?id=BcV9xmrpn
    Стоит обращать внимание на сырьё: натуральное дерево, прочный металл и безвредные покрытия.
    Практичность мебели выражается в наличии ящиков и регулировок под разные нужды.
    Бюджет также имеет значение, но экономия на данных товарах способна обернуться дополнительным издержкам на лечение или замену.
    Поэтому, предпочитайте надёжных производителей с официальными обязательствами и сертификатами.

  26. BrandonHoomb's avatar BrandonHoomb says:

    Удачный выбор офисной обстановки напрямую влияет на самочувствие и продуктивность персонала.
    Важнейший фактор — это эргономичность кресел и столов.
    Качественная корпусная мебель способна уменьшать усталость и профилактировать заболевания опорно-двигательного аппарата.
    Не менее значим внешний облик изделий, ведь он формирует образ компании для клиентов и гостей.
    https://cookmaster.gucci1.ru/redirect.php?id=iNbNEnu
    Рекомендуется присматриваться на материалы: массив, качественный стальной каркас и безвредные пропитки.
    Функциональность мебели выражается в наличии систем хранения и регулировок под разные задачи.
    Бюджет также имеет роль, но скупость на данных товарах способна обернуться скрытым расходам на ремонт или больничные.
    Поэтому, выбирайте проверенных производителей с гарантией и документацией соответствия.

  27. WishHour.Com's avatar WishHour.Com says:

    Just searching for this exact trend and your analysis on stitched fashion are incredible.
    Love the insight!

  28. ShanepiliA's avatar ShanepiliA says:

    Pretty! This has been an incredibly wonderful article. Many thanks for providing this information.
    sweepstakes casinos

  29. BrandonHoomb's avatar BrandonHoomb says:

    В наши дни сеть представляет собой неотъемлемой составляющей нашей повседневности.
    Всемирная сеть открывает мгновенный доступ к колоссальному массиву знаний.
    Благодаря интернету мы можем общаться с близкими и партнёрами в любой точке мира.
    Для труда, обучения и коммерции сеть стала в основной канал связи.
    https://rftimes.ru/news/2026-04-26-gazovye-kacheli-rossiya-mozhet-izvlech-vygodu-iz-nadvigayushchegosya-krizisa-na-rynke-golubogo-topliva
    Кроме того, интернет предлагает неисчерпаемые возможности для отдыха и личностного роста.
    При отсутствии выхода в сеть сегодня трудно представить как домашние, так и рабочие дела.
    Поэтому наличие к качественному интернету воспринимается базовой потребностью современного человека.

  30. คอนเทนต์นี้ อ่านแล้วได้ความรู้เพิ่ม ครับ
    ผม เพิ่งเจอข้อมูลเกี่ยวกับ เรื่องที่เกี่ยวข้อง

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

  31. Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me.

  32. Tez888's avatar Tez888 says:

    Responsible gambling means maintaining control over your hours and budget.
    This approach includes setting limits prior to you begin betting.
    You should never chase lost money.
    Tez888
    Safe play also requires recognizing that outcomes are based on luck, not skill.
    This promotes having frequent breaks and steering clear of betting when stressed or intoxicated.
    Recognized tools like deposit limits and time-outs assist players remain in healthy condition.
    At its core, responsible gambling is about having fun with the activity as entertainment, not as a way to make money.

  33. betflik22's avatar betflik22 says:

    Thank you for the good writeup. It in fact was a amusement account it.
    Look advanced to far added agreeable from you!
    By the way, how can we communicate? betflik22

  34. LhanepiliA's avatar LhanepiliA says:

    Whats up are using WordPress for your site platform? I’m new to the blog world but I’m trying to get started and create my own. Do you require any html coding expertise to make your own blog? Any help would be really appreciated!
    buy cannabis online for xxx adult porn video

  35. Данный софт является раскрученным софтом для массовой создания учётных записей и размещения сообщений на блогах.
    Эта программа может преодолевать различные ограничения, например графические тесты.
    Прогон веб-ресурсов обеспечивает оперативно увеличивать ссылочный профиль.
    sites.google.com
    Некоторые оптимизаторы задействуют этот софт для раскрутки в том числе конкурентных сферах.
    Функционирование с софтом XRumer подразумевает сноровки и точных настроек.
    При неправильном использовании можно запросто получить бан от поисковиков и ухудшение ранжирования.
    Несмотря на все минусы, востребованность на такой софт сохраняется значительным.

Comments are closed.