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

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

    This website provides a lot of engaging and informative information.
    Here, you can explore a wide range of subjects that help you learn new things.
    Visitors will appreciate the materials shared on this site.
    All topics is organized clearly, making it pleasant to use.
    The materials are easy to understand.
    The site includes guides on various fields.
    If you want to find educational content, this site has a lot to offer.
    Overall, this site is a reliable place for information seekers.
    https://gidromet.info/

  2. NathanTor's avatar NathanTor says:

    This resource offers a lot of captivating and useful information.
    Here, you can find various materials that broaden your horizons.
    Users will appreciate the content shared here.
    Every category is organized clearly, making it pleasant to use.
    The posts are easy to understand.
    The site includes recommendations on many areas.
    Whether you’re looking for useful facts, this site has what you’re looking for.
    In general, this site is a great source for information seekers.
    https://xevanio.de/

  3. Charlesspape's avatar Charlesspape says:

    Casino Roulette: Spin for the Ultimate Thrill
    Experience the timeless excitement of Casino Roulette, where every spin brings a chance to win big and feel the rush of luck. Try your hand at the wheel today at https://k8o.jp/ !

  4. Kevinbof's avatar Kevinbof says:

    Оформление ПМЖ за границей становится всё более популярным среди жителей России.
    Такой статус даёт дополнительные перспективы для путешествий.
    ВНЖ помогает легче пересекать границы и избегать визовых ограничений.
    Помимо этого такой документ может укрепить уверенность в будущем.
    Паспорт Италии
    Большинство граждан рассматривают возможность переезда как путь к независимости.
    Имея ВНЖ или второй паспорт, человек легко открыть бизнес за рубежом.
    Разные направления предлагают индивидуальные возможности получения статуса резидента.
    Вот почему тема получения становится приоритетной для тех, кто ищет стабильность.

  5. NathanTor's avatar NathanTor says:

    This resource contains a lot of captivating and valuable information.
    Here, you can learn about many topics that help you learn new things.
    Visitors will appreciate the information shared here.
    Each section is thoughtfully designed, making it convenient to use.
    The content are written clearly.
    There are tips on numerous themes.
    No matter if you seek practical advice, this site has everything you need.
    Overall, this resource is a valuable hub for people who enjoy discovering new things.
    https://gidromet.info/

  6. NathanTor's avatar NathanTor says:

    This website features a lot of fascinating and informative information.
    On this platform, you can explore many topics that help you learn new things.
    Users will benefit from the content shared here.
    Every category is thoughtfully designed, making it simple to use.
    The materials are presented professionally.
    It’s possible to find tips on different subjects.
    Whether you’re looking for useful facts, this site has something for everyone.
    All in all, this platform is a valuable hub for curious minds.
    https://roborant.info/

  7. Inscreva-se's avatar Inscreva-se says:

    Thanks for sharing. I read many of your blog posts, cool, your blog is very good.

  8. trafficedge.click – Bookmarked this immediately, planning to revisit for updates and inspiration.

  9. Huey Rosian's avatar Huey Rosian says:

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

  10. promostreamx.click – Appreciate the typography choices; comfortable spacing improved my reading experience.

  11. rankhive.click – Loved the layout today; clean, simple, and genuinely user-friendly overall.

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

  13. promostreamx.click – Appreciate the typography choices; comfortable spacing improved my reading experience.

  14. Hank Sircy's avatar Hank Sircy says:

    rankhive.click – Mobile version looks perfect; no glitches, fast scrolling, crisp text.

  15. Troy Lucus's avatar Troy Lucus says:

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

  16. marketblaze.click – Loved the layout today; clean, simple, and genuinely user-friendly overall.

  17. Dodie Nori's avatar Dodie Nori says:

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

  18. clickvelocity.click – Navigation felt smooth, found everything quickly without any confusing steps.

  19. adpilot.click – Loved the layout today; clean, simple, and genuinely user-friendly overall.

  20. clickvelocity.click – Color palette felt calming, nothing distracting, just focused, thoughtful design.

  21. adpilot.click – Color palette felt calming, nothing distracting, just focused, thoughtful design.

  22. Cody Cutlip's avatar Cody Cutlip says:

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

  23. promoverse.click – Appreciate the typography choices; comfortable spacing improved my reading experience.

  24. marketcraft.click – Pages loaded fast, images appeared sharp, and formatting stayed consistent.

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

  26. Peterhap's avatar Peterhap says:

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

  27. Peterhap's avatar Peterhap says:

    Получение второго гражданства за границей становится всё более важным среди россиян.
    Такой статус предоставляет широкие горизонты для работы и бизнеса.
    ВНЖ помогает легче пересекать границы и избегать визовых ограничений.
    Также такой документ может повысить уровень личной безопасности.
    Гражданство за Инвестиции
    Все больше людей рассматривают ПМЖ как путь к независимости.
    Оформляя ВНЖ или второй паспорт, человек получить образование за рубежом.
    Многие государства предлагают свои программы получения гражданства.
    Именно поэтому тема получения становится особенно актуальной для тех, кто планирует развитие.

  28. Peterhap's avatar Peterhap says:

    Наличие второго паспорта за границей становится всё более важным среди граждан РФ.
    Такой выбор открывает дополнительные перспективы для жизни.
    Гражданство другой страны помогает свободнее передвигаться и упрощать поездки.
    Также такой документ может укрепить уровень личной безопасности.
    Гражданство Греции
    Все больше людей рассматривают ПМЖ как инструмент защиты.
    Имея ВНЖ или второй паспорт, человек расширить свои связи за рубежом.
    Каждая страна предлагают индивидуальные возможности получения вида на жительство.
    Именно поэтому тема получения становится приоритетной для тех, кто ищет стабильность.

  29. clickengine.click – Appreciate the typography choices; comfortable spacing improved my reading experience.

  30. rankpilotx.click – Navigation felt smooth, found everything quickly without any confusing steps.

  31. Chi Lacovara's avatar Chi Lacovara says:

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

  32. clickengine.click – Color palette felt calming, nothing distracting, just focused, thoughtful design.

  33. Emily Morey's avatar Emily Morey says:

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

  34. ranksphere.click – Pages loaded fast, images appeared sharp, and formatting stayed consistent.

  35. Maren Colt's avatar Maren Colt says:

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

  36. advelocity.click – Navigation felt smooth, found everything quickly without any confusing steps.

  37. leadstreamx.click – Found practical insights today; sharing this article with colleagues later.

  38. Greg Symmes's avatar Greg Symmes says:

    rankrocket.click – Mobile version looks perfect; no glitches, fast scrolling, crisp text.

  39. Letty Mammen's avatar Letty Mammen says:

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

  40. Ignacio Nery's avatar Ignacio Nery says:

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

  41. viralboost.click – Appreciate the typography choices; comfortable spacing improved my reading experience.

  42. Kevinbof's avatar Kevinbof says:

    Оформление ПМЖ за границей становится всё более востребованным среди граждан РФ.
    Такой вариант даёт новые возможности для работы и бизнеса.
    ВНЖ помогает беспрепятственно путешествовать и избегать визовых ограничений.
    Также наличие второго статуса может улучшить уровень личной безопасности.
    Паспорт Испании
    Все больше людей рассматривают второе гражданство как инструмент защиты.
    Получив ВНЖ или второй паспорт, человек расширить свои связи за рубежом.
    Разные направления предлагают разные условия получения вида на жительство.
    Вот почему тема получения становится особенно актуальной для тех, кто ищет стабильность.

  43. Kevinbof's avatar Kevinbof says:

    Наличие второго паспорта за границей становится всё более популярным среди граждан РФ.
    Такой вариант открывает новые возможности для жизни.
    Второй паспорт помогает беспрепятственно путешествовать и избегать визовых ограничений.
    Помимо этого наличие второго статуса может повысить уверенность в будущем.
    Паспорт Вануату
    Многие россияне рассматривают ПМЖ как инструмент защиты.
    Имея ВНЖ или второй паспорт, человек легко открыть бизнес за рубежом.
    Каждая страна предлагают разные условия получения вида на жительство.
    Вот почему идея второго паспорта становится приоритетной для тех, кто ищет стабильность.

  44. rankrocket.click – Content reads clearly, helpful examples made concepts easy to grasp.

  45. Miles Pandy's avatar Miles Pandy says:

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

  46. Nigel Koroma's avatar Nigel Koroma says:

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

  47. clickmagnetix.click – Pages loaded fast, images appeared sharp, and formatting stayed consistent.

  48. leadcraft.click – Color palette felt calming, nothing distracting, just focused, thoughtful design.

  49. Lynn Freidin's avatar Lynn Freidin says:

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

  50. growthbeacon.click – Navigation felt smooth, found everything quickly without any confusing steps.

Comments are closed.