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. Hi there, You’ve done an excellent job. I will definitely digg it and for my part suggest to my friends. I’m confident they will be benefited from this website.

  2. At this time it appears like BlogEngine is the top blogging platform out there right now. (from what I’ve read) Is that what you’re using on your blog?

  3. roof repair's avatar roof repair says:

    With thanks! An abundance of write ups.

  4. Честно говоря, — какой сервис выбрать для международных платежей. Эксперты рекомендуют вот этот обзор: перевод за границу онлайн перевод за границу онлайн Если коротко, — не все способы одинаково выгодны. Согласитесь, очередной международный перевод — это потеря времени без нормальной инфы. И ещё момент, — до любой операции проверьте несколько вариантов. Без этого легко попасть на лишние траты. Резюмируя, — не поленитесь проверить информацию.

  5. Aw, this was a very nice post. Spending some time and actual effort to create a great article… but what can I say… I procrastinate a whole lot and don’t seem to get anything done.

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

  7. Thanks, Terrific stuff!

  8. Superb material, Kudos!

  9. At this time it looks like BlogEngine is the preferred blogging platform available right now. (from what I’ve read) Is that what you’re using on your blog?

  10. Okay folks gather round — another Miami rental horror story coming at you. You see this killer deal online — brand new Mercedes, unlimited miles, price that makes you want to book immediately. Plus they put a $5000 hold on your card and tell you “it’s just standard procedure”. Thirteen years in South Florida and these clowns still almost get me. luxury car rental in miami. Miami without proper wheels is basically a nightmare. South Beach night out, Design District shopping spree, or a spontaneous Keys trip — AC must be arctic cold and unlimited miles non-negotiable. I’ve tested maybe 70 rental companies across Dade, Broward, and Palm Beach. Finally found one outfit that actually delivers what’s promised. Here’s the only straight shooter for premium rides across South Florida
    rent a porsche miami https://luxury-car-rental-miami-13.com also bring polarized shades unless you enjoy driving into the sun like a blind bat every evening. Anyway glad there’s at least one honest rental joint left in this town.

  11. Currently it appears like BlogEngine is the best blogging platform out there right now. (from what I’ve read) Is that what you’re using on your blog?

  12. 小鸟入口's avatar 小鸟入口 says:

    Wow that was odd. I just wrote an incredibly long comment but after I clicked submit my comment didn’t appear. Grrrr… well I’m not writing all that over again. Regardless, just wanted to say excellent blog!

  13. Wow that was strange. I just wrote an extremely long comment but after I clicked submit my comment didn’t show up. Grrrr… well I’m not writing all that over again. Anyways, just wanted to say superb blog!

  14. 银河登录's avatar 银河登录 says:

    Currently it seems like Drupal is the best blogging platform available right now. (from what I’ve read) Is that what you are using on your blog?

  15. CR电竞's avatar CR电竞 says:

    Wow that was odd. I just wrote an really long comment but after I clicked submit my comment didn’t show up. Grrrr… well I’m not writing all that over again. Anyhow, just wanted to say great blog!

  16. Hey there, You have done an incredible job. I’ll certainly digg it and in my view recommend to my friends. I’m sure they will be benefited from this web site.

  17. Hey there, You have performed an excellent job. I’ll definitely digg it and for my part recommend to my friends. I am sure they will be benefited from this site.

  18. I’ve been through the wringer more times than I care to admit. You see this incredible deal online — top-end BMW, zero excess, price that seems too good to be true. Then you actually go to pick up the car. Plus they slap a $6000 hold on your credit card and say “don’t worry, it’s just a pre-authorization”. Fifteen years in South Florida and these clowns still almost catch me. luxury car rental miami fl. Miami without proper wheels is basically a hostage situation. leather seats that won’t brand your back in the July heat. I’ve tested maybe 80 rental companies across Dade, Broward, Palm Beach, and Monroe. Finally found one outfit that actually delivers what’s promised. prices change daily so check before the holiday crowd hits:
    exotic car rental south beach miami exotic car rental south beach miami Yeah parking in Brickell will cost you a nice steak dinner — but that’s just how it is down here. drive safe and definitely skip that “paint protection” upsell — complete waste of cash.

  19. At this time it seems like WordPress is the preferred blogging platform available right now. (from what I’ve read) Is that what you are using on your blog?

  20. Hey I know this is off topic but I was wondering if you knew of any widgets I could add to my blog that automatically tweet my newest twitter updates. I’ve been looking for a plug-in like this for quite some time and was hoping maybe you would have some experience with something like this. Please let me know if you run into anything. I truly enjoy reading your blog and I look forward to your new updates.

  21. Wow that was strange. I just wrote an incredibly long comment but after I clicked submit my comment didn’t show up. Grrrr… well I’m not writing all that over again. Anyways, just wanted to say excellent blog!

  22. Wow that was strange. I just wrote an very long comment but after I clicked submit my comment didn’t appear. Grrrr… well I’m not writing all that over again. Anyways, just wanted to say superb blog!

  23. I’ve been burned more times than a cheap steak at a tourist trap. You find this amazing offer online — beautiful car, great rate, everything seems perfect. Completely different car waiting for you — smells like stale cigarettes, check engine light glowing, and that “great rate”? Doesn’t include the mandatory $35 daily toll pass, the $200 cleaning fee, or the $75 “after-hours pickup” charge. Sixteen years in Miami and these tricks still pop up like bad weeds. luxury car rental miami fl. Miami without real wheels is basically a slow death. Design District shopping, late-night South Beach cruising, or a spontaneous Keys trip — AC must be freezing and unlimited miles or walk. most are just pretty websites hiding the same old garbage. no tricks, no switch, no surprise fees. Here’s the only honest place for premium rentals across South Florida
    exotic car rental south beach miami exotic car rental south beach miami also bring good sunglasses unless you like driving blind. drive safe and skip the extra insurance upsell, it’s a joke.

  24. Метод УВТ представляет собой эффективный способ лечения, базирующийся на применении звуковых импульсов.
    Эта процедура активизирует микроциркуляцию и запускает механизмы восстановления клеток.
    УВТ широко используется для терапии патологий опорно-двигательного аппарата – например, при тендинитах и пяточной шпоре.
    https://novogireevo-klinika.ru/
    Ключевые преимущества способа – это неинвазивность, практическая терпимость и высокая результативность уже после нескольких процедур.
    Обычно приём длится около 10–20 минут и проводится в поликлинике без стационара.
    В итоге пациенты наблюдают значительное уменьшение болей и восстановление свободы подвижности в поражённой области.

  25. Excellent pieces. Keep writing such kind of information on your blog. Im really impressed by your site.

  26. Currently it sounds like BlogEngine is the best blogging platform available right now. (from what I’ve read) Is that what you’re using on your blog?

  27. 广发软件's avatar 广发软件 says:

    Hey I know this is off topic but I was wondering if you knew of any widgets I could add to my blog that automatically tweet my newest twitter updates. I’ve been looking for a plug-in like this for quite some time and was hoping maybe you would have some experience with something like this. Please let me know if you run into anything. I truly enjoy reading your blog and I look forward to your new updates.

  28. Hey I know this is off topic but I was wondering if you knew of any widgets I could add to my blog that automatically tweet my newest twitter updates. I’ve been looking for a plug-in like this for quite some time and was hoping maybe you would have some experience with something like this. Please let me know if you run into anything. I truly enjoy reading your blog and I look forward to your new updates.

  29. Alright let me drop some truth about the Miami rental scene — it’s an absolute minefield. You spot a tempting offer online: brand new Porsche, unlimited miles, price that makes you click instantly. Totally different vehicle waiting for you — check engine light on, curb rash on every rim, and that “tempting price”? Doesn’t include the mandatory $35 daily toll pass or the $250 cleaning fee they sneak in at the end. Ten years in South Florida and these jokers still almost catch me slipping. miami luxury car rental. Miami without solid wheels is basically a punishment. leather seats that won’t cook your back in the July heat. most are shiny websites hiding the same beat-up fleet with fresh wax. Finally found one outfit that actually delivers what’s promised. prices change by the hour so don’t wait around:
    rental car in miami florida https://luxury-car-rental-miami-10.com Yeah parking in Brickell will cost you a nice dinner — but that’s just how it is down here. Anyway glad there’s at least one honest rental joint left in this town.

  30. Aw, this was an incredibly nice post. Spending some time and actual effort to generate a very good article… but what can I say… I procrastinate a whole lot and never seem to get anything done.

  31. At this time it looks like Expression Engine is the preferred blogging platform available right now. (from what I’ve read) Is that what you are using on your blog?

  32. At this time it appears like Movable Type is the top blogging platform out there right now. (from what I’ve read) Is that what you are using on your blog?

  33. Hey I know this is off topic but I was wondering if you knew of any widgets I could add to my blog that automatically tweet my newest twitter updates. I’ve been looking for a plug-in like this for quite some time and was hoping maybe you would have some experience with something like this. Please let me know if you run into anything. I truly enjoy reading your blog and I look forward to your new updates.

  34. Selamat malam, ada yang tahu slot tiger? 22Bet

  35. Currently it sounds like Drupal is the top blogging platform available right now. (from what I’ve read) Is that what you are using on your blog?

  36. Great post, Jesse. I’ve been using Swagger for a while, but your explanation of how to structure comments for clarity really helped me clean up my own API documentation. Do you have any tips for handling deprecated endpoints specifically?

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

  38. Yesterday, while I was at work, my sister stole my apple 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 broken and she has 83 views. I know this is totally off topic but I had to share it with someone!

  39. Today, while I was at work, my cousin stole my iPad and tested to see if it can survive a 30 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!

  40. The other day, while I was at work, my cousin stole my apple ipad and tested to see if it can survive a 30 foot drop, just so she can be a youtube sensation. My iPad is now destroyed and she has 83 views. I know this is completely off topic but I had to share it with someone!

  41. Best score tracking site I’ve found so far.

  42. Just want to say your article is as astounding. The clearness in your post is just nice and i could assume you are an expert on this subject. Well with your permission allow me to grab your feed to keep up to date with forthcoming post. Thanks a million and please carry on the rewarding work.

  43. Simply desire to say your article is as surprising. The clearness in your post is simply excellent and i could assume you are an expert on this subject. Fine with your permission let me to grab your RSS feed to keep updated with forthcoming post. Thanks a million and please continue the gratifying work.

  44. Just wish to say your article is as astonishing. The clarity in your post is simply cool and i could assume you are an expert on this subject. Well with your permission let me to grab your feed to keep updated with forthcoming post. Thanks a million and please carry on the enjoyable work.

Comments are closed.