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. The pagination example is a great practical application for Swagger comments. I’ve often found that explaining complex API structures can be challenging, and well-documented endpoints make a huge difference for developers consuming them. It’s interesting to see how you break down the `Get` method with `showDeleted`, `pageNumber`, and `pageSize`. When I’m building out tools for communication, like my MorseTranslator, clear documentation is absolutely crucial, even for something as seemingly simple as translating characters. It’s the same principle here – making the API’s behavior transparent and predictable.

  2. GichardAmomi's avatar GichardAmomi says:

    The structure of this post makes the ideas simple to understand and helps keep the overall discussion interesting for readers.

    casino en ligne retrait instantane

  3. OrbitDash's avatar OrbitDash says:

    The breakdown of paging with `pageNumber` and `pageSize` in the `Get` method makes a lot of sense for handling large datasets. It’s a clean way to avoid overwhelming the client. I also appreciate how you’re tying it back to Swagger comments, which is crucial for making APIs understandable. I’ve been experimenting with similar API documentation strategies on OrbitDash, and clear comments really do make a difference in how easily other developers (or even your future self!) can interact with the API. It’s like having a well-written instruction manual for your code.

  4. DichaelAlono's avatar DichaelAlono says:

    One thing that stands out about this post is how naturally the ideas are presented, because the discussion flows in a way that feels both engaging and understandable without becoming too heavy for readers to follow.

    casino en ligne retrait immediat

  5. Haroldser's avatar Haroldser says:

    Разумный подход к азарту в онлайн-казино — это совокупность правил, направленных на защиту психики игроков.
    Эта концепция предполагает добровольное ограничение времени и денег на сессии.
    Игроку рекомендуется предварительно устанавливать бюджет и не превышать его ни при каких обстоятельствах.
    Платформы честного i-gaming должны предоставлять инструменты для самопроверки и тайм-аутов.
    Маркерами проблемы служат потребность отыграться и игнорирование реальными делами.
    Ответственная игра помогает воспринимать к площадке как к развлечению, а не инструменту дохода.
    За счёт соблюдения этих установок азарт сохраняется в безопасных границах, без вреда для личности.
    https://beer-logic.ru/publication/547-teplosnabzhenie-v-dnr-pod-lupoy-pryamaya-liniya-s-chelovekom-kotoryy-znaet-o-goryachey-vode-vsyo.html

  6. If you want to get a good deal from this post then you have to apply such techniques to your
    won web site.

  7. Restore Old Photos provides fast, high-quality restoration for black-and-white and color photos with one click.

  8. KevinGog's avatar KevinGog says:

    Моя рекомендация по seo — эта компания, подробнее тут <a href=
    https://www.rctech.net/forum/members/mihaylovdigital-536382.html

  9. The pagination approach you’ve detailed here, especially with `pageNumber` and `pageSize`, makes a lot of sense for handling large datasets. It’s so much more efficient than pulling everything at once. I’ve seen situations where a lack of proper pagination led to significant performance bottlenecks.

    Adding Swagger comments to annotate this is crucial for clear API documentation. I’m curious, do you find that documenting parameters like `showDeleted` directly in the Swagger comments is usually sufficient, or do you also rely on separate markdown files for more complex explanations? It’s a similar challenge when estimating material needs; clearly defining the input parameters is key to an accurate result. I wrote about a similar approach on Concrete Calculator and found that precise parameter definition dramatically improved user outcomes.

  10. hiteBize's avatar hiteBize says:

    На данном сайте имеется ценная сведения.
    На этом портале можно найти немало полезного для себя.
    Данный ресурс поможет изучить в разных ситуациях.
    Советуем детально прочитать размещенные здесь публикации.
    https://english.zlatamoda.ru/

  11. Timsothybioli's avatar Timsothybioli says:

    I really like the way this post combines clarity and straightforward presentation while still keeping the overall discussion interesting and meaningful.

    Bet Way Casino

  12. JamesSog's avatar JamesSog says:

    MexiCare Direct: MexiCare Direct – farmacia online usa

  13. The pagination example you’ve outlined is a really practical way to handle potentially large datasets, and I appreciate you walking through the logic of how `pageNumber` and `pageSize` translate to specific record ranges. It makes perfect sense for efficiency. I’ve been exploring similar data handling strategies for game content, and documenting these endpoints clearly is crucial for anyone using them, whether it’s another developer or even yourself down the line. I actually wrote about a similar approach to documenting API endpoints and found that thorough XML comments, as you’re demonstrating, significantly reduce integration friction. It’s like providing a clear map for navigating your API.

  14. IsmaelNiz's avatar IsmaelNiz says:

    This was exactly the kind of trustworthy reading material I was looking for to fill my afternoon break, and I truly value the balanced approach you used to cover all the necessary bases without any distractions.

    site de paris sportif hors arjel

  15. mood gummies's avatar mood gummies says:

    The surface and color of this look freshly laundered and cultured, with no cloudiness or residue. The fiasco pours smoothly, and the exceed seals tightly. Inclusive, it feels like a thoughtfully made outcome designed with je sais quoi in mind.

  16. OrbitDash CC's avatar OrbitDash CC says:

    The pagination example you’ve laid out makes perfect sense for managing large datasets, and I appreciate the clear breakdown of how `pageNumber` and `pageSize` work together. It’s a much more efficient approach than returning everything at once. I also found your explanation of using XML comments for Swagger annotations incredibly helpful. It’s a detail that’s easy to overlook but makes a huge difference in API usability. I’ve been exploring ways to improve API documentation myself, and this post really solidifies the value of embedding that information directly. It reminds me of some of the principles behind clear instructions, similar to how we approach game design on OrbitDash CC – making sure the player knows exactly what to do next.

  17. FrontWars.io's avatar FrontWars.io says:

    The pagination example you’ve laid out makes perfect sense for managing large datasets, and I appreciate the clear breakdown of how `pageNumber` and `pageSize` work together. It’s a much more efficient approach than fetching everything at once. I found myself thinking about how crucial these kinds of annotations are, especially when working on larger teams or when APIs are meant to be consumed by external developers. Having well-documented endpoints, like what Swagger provides with these comments, really streamlines the integration process. I wrote about a similar approach for simplifying API documentation on FrontWars.io and found that clear comments were the bedrock of a smooth experience for anyone interacting with the API. It definitely saves a lot of head-scratching down the line!

  18. Awesome! Its genuinely remarkable post, I have got much clear idea about from
    this piece of writing.

  19. AlbertWhawl's avatar AlbertWhawl says:

    9 6 15 матрица судьбы читайте на омниватике (omnivatic.com) – полный астрологический прогноз для каждого

  20. FrontWars.io's avatar FrontWars.io says:

    The concept of paginating large data sets, as you’ve illustrated with the `Get` method’s `pageNumber` and `pageSize` parameters, is really crucial for efficient API design. It’s a much better approach than fetching everything at once, which can quickly become unmanageable. I’ve found that clear documentation, especially with tools like Swagger, makes a huge difference for developers consuming an API. Thinking about how to best document these kinds of parameter variations, like `showDeleted`, is where the real value of Swagger comments shines. It clarifies intent immediately. For anyone building out APIs, understanding these documentation aspects is key, and I’ve touched on some related strategies for clear API communication on FrontWars.io.

  21. roomflip.pro's avatar roomflip.pro says:

    The explanation of how Swagger comments work with the `CarController`’s `Get` method is a great way to visualize the process. It makes sense that breaking down large data sets into paginated responses, like you’ve demonstrated with `pageNumber` and `pageSize`, is crucial for efficient API design. This approach not only reduces the data transferred but also improves the responsiveness for the end-user. I’ve found that similar pagination strategies are vital in applications where users might be browsing large inventories or project lists. In fact, I wrote about a similar approach for handling large datasets and improving user experience on roomflip.pro and found that clear API documentation, like what Swagger provides, is key to making those features easy to integrate and understand.

  22. Randyneall's avatar Randyneall says:

    stromectol 3 mg tablet Institute for Clinical Pharmacology & Safety stromectol medication

  23. Wordleos's avatar Wordleos says:

    The idea of paginating the `Get` method is a smart move, especially when dealing with potentially large datasets like car records. The example of `Get(false, 3, 4)` clearly illustrates how it would work to fetch specific chunks of data, which is crucial for performance. I’ve been thinking a lot about how to optimize data retrieval in my own projects, and this approach is definitely something to consider. You mentioned using XML comments for documentation, and I’ve found that consistent documentation is key for maintainability. I actually wrote about a similar approach to API documentation and best practices on Wordleos and found that clear, concise comments make a huge difference for anyone consuming the API later on.

  24. HiramLuh's avatar HiramLuh says:

    amoxicillin 500mg capsules antibiotic Infectious Disease & Antimicrobial Research Institute amoxicillin 500mg price canada

  25. The breakdown of how `pageNumber` and `pageSize` interact to determine which records are returned is really helpful. I particularly liked the concrete example of `Get(false,3,4)` – it makes the pagination concept so much clearer than just abstractly describing it. It’s interesting how much more organized an API can become with just these simple additions. I’ve been playing around with generating different text styles online, and even simple formatting like using a Bold Text Generator can make a difference in readability, so I can see how detailed comments would be even more impactful for API documentation. It makes me wonder how many developers overlook the value of robust XML comments.

  26. The explanation of how `pageNumber` and `pageSize` work together to define record ranges is a great way to visualize the data retrieval. The example of `Get(false,3,4)` clearly illustrates this, making it easy to grasp the concept of retrieving specific pages of data rather than the entire dataset. This is such a crucial optimization for APIs that deal with potentially large amounts of information. I’ve found that clearly defining these pagination parameters upfront saves a lot of back-and-forth when integrating with an API. It reminds me of the importance of upfront design in other areas, like planning permanent body art; I wrote about a similar approach on Before You Ink and found that thorough documentation and clear definitions, even for something as seemingly straightforward as pagination, prevent much larger issues down the line.

  27. SteveLat's avatar SteveLat says:

    Хорошие поставщики вакуумного оборудования для промышленности, смотрите здесь <a href=
    https://stocktwits.com/Olga1992

  28. OrbitDash's avatar OrbitDash says:

    The way you’ve broken down the `Get` method with `showDeleted`, `pageNumber`, and `pageSize` parameters is really clear, especially the explanation of how page numbers translate to record ranges. It’s so easy to overlook the impact of pagination on payload sizes, and I’ve definitely seen projects bog down because of it. Getting that right from the start can save a ton of headaches down the line. It reminds me a bit of how optimizing game performance relies on efficient data handling, ensuring smooth gameplay without lag. I wrote about a similar approach to managing data flow in a performance-critical context on OrbitDash and found that clear documentation, much like you’re advocating for with Swagger comments, was key to everyone being on the same page.

  29. Josephned's avatar Josephned says:

    what are the side effects of gabapentin withdrawal Neurontin does gabapentin cause sleep apnea

  30. The way you’ve implemented the pagination logic using zero-based indexing for the pageNumber is a smart way to handle large datasets, but it highlights just how critical clear documentation becomes for the end consumer. Without those XML comments you’re discussing, a developer might easily assume a one-based index and end up fetching the wrong slice of data, which can lead to some really frustrating debugging sessions later on. I’ve seen similar issues when building out complex data structures for gaming tools; if the pagination parameters aren’t explicitly annotated in the Swagger UI, users can’t intuitively grasp how the offsets work. I actually touched on the importance of precise data retrieval and documentation when I was organizing information on KCD2Quest, as even a small misunderstanding of how data is paginated can break a user’s experience. Properly annotating these parameters ensures that the “magic” happening inside the repository is actually transparent to whoever is calling the endpoint.

  31. The distinction you make regarding the zero-based indexing for the pageNumber parameter is a crucial detail that often trips up developers integrating with an API for the first time. If a consumer assumes a one-based index, they’ll constantly be offset by an entire page of data, which can be a nightmare to debug in production. Using XML comments to explicitly document that behavior within Swagger is definitely the right move for preventing those kinds of integration errors.

    I’ve found that when building complex tools that rely on precise data retrieval, like the resource planning guides I work on at Wizard Alchemy Hub, even a slight misunderstanding of pagination can lead to massive errors in calculation. Clear documentation via Swagger doesn’t just help the developer; it protects the integrity of the data being consumed. It would be interesting to see if you plan to cover how to document the specific response models or error codes next, as that’s usually the next hurdle once the parameters are well-defined.

  32. OLanepiliA's avatar OLanepiliA says:

    The structure of this post makes the ideas clear and helps keep the overall discussion enjoyable for readers.

    купить inmode Plus/Forma

  33. I am really impressed with your writing skills as well as with the layout on your weblog.
    Is this a paid theme or did you modify it yourself? Either way keep up the nice quality writing, it’s rare to see a nice blog like
    this one today.

  34. The way you explained the zero-based indexing for the `pageNumber` is a lifesaver, because without that specific clarification, a frontend dev might assume a 1-based system and end up requesting the wrong set of data entirely. I’ve seen so many API integrations fail simply because the documentation didn’t explicitly state whether the first page was 0 or 1. When dealing with large datasets, as you mentioned with the car database, having those XML comments clearly defining the `pageSize` and `showDeleted` parameters is the difference between a smooth integration and a debugging nightmare. I actually find myself applying a similar logic of strict categorization and clear labeling when I’m organizing data for my guides on Pokopia Crystals, especially when tracking specific item locations or event parameters. If the metadata isn’t precise, the user experience falls apart. Documentation shouldn’t just be an afterthought; it’s essentially the user interface for the developer.

  35. TimothySet's avatar TimothySet says:

    rybelsus para que sirve en espaГ±ol us obesity science

  36. The distinction you make regarding zero-based indexing for the `pageNumber` is a crucial detail that often gets lost in documentation, leading to “off-by-one” errors for the frontend developers consuming the API. While pagination is clearly the right move to prevent massive payloads, I’ve found that the real magic happens when the Swagger annotations actually describe the constraints of those parameters—like defining a minimum value for `pageSize` so a user doesn’t accidentally request a million records in a single call.

    Documenting these edge cases via XML comments makes the UI much more intuitive for testing. It reminds me of how much more engaging a complex system becomes when the rules are clearly defined; for instance, when I play strategy games on Maze Craze Online, the difficulty only feels fair when the mechanics are transparent. Applying that same level of clarity to your `CarController` through Swagger ensures that anyone using your endpoint knows exactly what to expect without having to dig into your repository logic.

Comments are closed.