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. AI Image Editor – Free Online AI Image Editor for photo enhancement and editing.

  2. Restore Old Photos is a professional service that brings your precious memories back to life with advanced photo restoration technology

  3. IsmaelNiz's avatar IsmaelNiz says:

    This post has a very good balance between being useful and staying accessible, because the discussion remains easy to follow while still offering enough depth to make readers think about the topic more carefully.

    Кони ебут Лаврова

  4. This was a very informative read — thank you for taking the time to publish it. Check out this free QR Code Generator — supports custom branding, scan tracking, and editable URLs. Perfect for business cards and marketing campaigns.

  5. Absolutely loved this post — thanks a ton for sharing! This free Morse Code Translator is a handy tool for translating morse code to text and back. Very useful for quick decoding.

  6. Thank you for the insightful post. Learned something new today. Explore thousands of free piano sheets roblox with easy notation. Master popular songs from anime and pop music using an interactive virtual piano practice tool.

  7. hiteBize's avatar hiteBize says:

    Дамская сумка — это не только аксессуар, но и важный элемент стиля.
    Она помогает аккуратно носить множество необходимые вещицы — от ключей до косметики.
    Сумка может как подчеркнуть плюсы фигуры, так и визуально скорректировать пропорции.
    Разнообразие моделей — шоппер, изящный клатч, кросс-боди — позволяет выбрать вариант на любой случай.
    Вид ткани тоже играет роль: натуральная кожа, велюр, полиэстер определяют долговечность и престижность.
    Цвет и фактура добавляют индивидуальность, делая даже базовую вещь в интересный лук.
    Поэтому вклад в качественную модель оправдывает себя каждый день удобством и стилем.
    https://pilot-club.ru/info/2026-06-01-neobychnaya-vstrecha-khrushchyov-monro-i-dostoevskiy-v-polnochnom-dialoge/

  8. hiteBize's avatar hiteBize says:

    Женская сумка — это не просто аксессуар, но и ключевой элемент образа.
    Она помогает организованно хранить все нужные мелочи — от ключей до косметики.
    Изделие может как акцентировать плюсы фигуры, так и визуально скорректировать соотношения.
    Многообразие фасонов — классические тоут, изящный клатч, практичный рюкзак — даёт подобрать вариант под любое событие.
    Материал тоже значим: натуральная кожа, мягкая замша, полиэстер задают долговечность и статусность.
    Цвет и фактура вносят индивидуальность, делая даже простую одежду в запоминающийся аутфит.
    Вот почему вклад в добротную модель окупается каждый день удобством и стилем.
    https://ipcfms.ru/read/171-kak-izbavitsya-ot-skrytykh-natsenok-v-produktovykh-magazinakh-i-sokhranit-byudzhet.html

  9. Steventum's avatar Steventum says:

    play game slot online casino in south africa

  10. AZEM BISTRO's avatar AZEM BISTRO says:

    Great post, Jesse! I’ve been using Swagger for a while now, but your breakdown of how to structure comments for better documentation really clarified a few things for me. Do you have any tips for handling complex nested models in Swagger without making the comments too verbose?

  11. Jamesacutt's avatar Jamesacutt says:

    https://easynorthrxs.shop/# canadian pharmacy no scripts

  12. Your style is so unique in comparison to other
    people I’ve read stuff from. I appreciate you for posting when you have
    the opportunity, Guess I will just bookmark this page.

  13. I love how you make complex topics easy to follow. Excellent work!

  14. Samuelsiz's avatar Samuelsiz says:

    фтубол читали когда нибудь что то подобное?

  15. hiteBize's avatar hiteBize says:

    На конкретном ресурсе представлена нужная материалы.
    Тут есть возможность получить множество ценного для решения задач.
    Представленный веб-сайт дает возможность изучить в разных проблемах.
    Рекомендуем подробно посмотреть размещенные здесь данные.
    https://pilot-club.ru/info/2026-05-22-shokoladnyy-tvorozhnyy-i-bananovyy-tri-keksa-kotorye-ne-podvedut-dazhe-samogo-neuverennogo-povara/

  16. OctavioAmoub's avatar OctavioAmoub says:

    MexiCare Direct: MexiCare Direct – mexico medication

  17. Restore Old Photos is a free online tool that uses AI to repair scratches, tears, and fading in vintage and damaged photos.

  18. Nicely expressed really. .

  19. Thomasblari's avatar Thomasblari says:

    Ordering medications online is extremely convenient.
    You can browse around the clock with no stepping out of your house.
    Digital pharmacies allow you to quickly compare prices and locate the lowest price.
    Your meds are delivered directly to your doorstep, saving time and hassle.
    iMedix patient reviews
    There’s no need to wait in long lines at a local store.
    When dealing with long-term conditions, auto refills ensure treatment stress‑free.
    Overall, digital shopping for meds saves your time and energy.

  20. Thomasblari's avatar Thomasblari says:

    Buying medicine online is incredibly handy.
    It’s possible to shop at any hour without stepping out of your house.
    Digital drugstores allow you to quickly check prices and find the lowest price.
    Your meds are sent directly to your door, cutting a trip and hassle.
    suhagra and nitrates
    There is no requirement to stand in annoying lines at a local store.
    For chronic illnesses, automatic refills make treatment stress‑free.
    In short, online shopping for medicine saves your time and energy.

  21. Thomasblari's avatar Thomasblari says:

    Getting medicine online is incredibly handy.
    One can purchase 24/7 without stepping out of your house.
    Internet drugstores let you quickly check costs and find the lowest deal.
    The meds are delivered straight to your doorstep, cutting a trip and effort.
    suhagra for erectile dysfunction
    There is no requirement to wait in long queues at a local store.
    When dealing with chronic conditions, auto reorders make treatment hassle‑free.
    To sum up, digital shopping for meds preserves your hours and peace of mind.

  22. Amazing a lot of terrific data!

  23. Use this free square face generator to design your own pixel avatar with 200+ customization items across 12 categories and download it instantly

  24. DichaelAlono's avatar DichaelAlono says:

    This post feels well explained and pleasant to read while keeping the discussion clear and comfortable for different readers online.

    https://gerardzwanenburg.nl/

  25. OctavioAmoub's avatar OctavioAmoub says:

    mexico pet pharmacy: MexiCare Direct – mexican pharmacies that ship to the united states

  26. The explanation of how `pageNumber` and `pageSize` work together to fetch specific data chunks is very clear. The example of `Get(false,3,4)` returning records 17-20 really solidifies the concept of pagination. It reminds me a bit of how I approach planning item combinations in Minecraft; you have to consider the “cost” (page size) and the “desired outcome” (page number) to get exactly what you need without wasting resources. I’ve written about a similar approach for optimizing item upgrades on my Minecraft enchantment Calculator and found that clear documentation upfront makes all the difference. It’s great to see that principle applied here with Swagger comments.

  27. Ai Photo Enhancer enhances images by increasing clarity, sharpness, and details.

  28. Concrete Calculator provides fast and accurate concrete calculations in cubic yards, cubic feet, and cubic meters.

  29. The idea of paginating API responses, especially for large datasets like a car database, makes so much sense. Avoiding the overhead of sending everything at once is a crucial optimization. I’m curious about how you handle edge cases with pagination, like when a user requests a page number that’s beyond the available data. Do you return an empty list, or is there a specific error code you prefer? It reminds me a bit of how we approach value calculations for items in games; you wouldn’t want to load absolutely every single item’s value at once when a user is just looking for a specific rarity. It’s all about efficient data retrieval. I wrote about a similar approach on Blox Fruits Trading and found that clear documentation for these methods, like what you’re showing with Swagger comments, is key for other developers to understand how to effectively use the API.

  30. Jamesacutt's avatar Jamesacutt says:

    http://easynorthrxs.com/# canadian compounding pharmacy

  31. The concept of paginating API responses, especially for large datasets like a car database, makes so much sense. Avoiding the overhead of sending everything at once is a crucial optimization. I’m curious, though, how do you typically handle edge cases with pagination? For instance, what happens if `pageNumber` is out of bounds, or if `pageSize` is excessively large or small? It’s something I’ve grappled with on Rivals Tools when developing features that need to manage large amounts of game data. Adding Swagger comments seems like the perfect way to clearly document these parameters and their expected behavior for consumers.

  32. Brat Generator allows you to generate viral minimalist green cover images.

  33. The explanation of how to implement pagination with `pageNumber` and `pageSize` in the `Get` method is a great practical example for anyone working with APIs. I particularly liked how you broke down the calculation for which records would be returned, like `Get(false, 3, 4)` returning records 17-20. It makes the concept of zero-based indexing and page sizes very clear. This kind of granular control is crucial for efficiency, especially when dealing with large datasets, much like how I focus on efficient service delivery when finding mobile detailing near me. It’s interesting to see how these principles of efficient data retrieval translate across different technical domains.

Comments are closed.