C# ASP.NET 5 - Designing Web APIs with Swagger aka OpenAPI Specification

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] [Applause] [Music] [Applause] [Music] okay it's 9 16. so we are ready to go again uh recording is running and as promised we are now going to design an api with a standard which is called open api specification or the the more the less formal name of that is called swagger swagger is a standard for describing apis what's the core idea of swagger and open api specification imagine that i gave you just a url for a server which offers a web api let's say api rain.rainasgradeserver.com and i tell you use this api your next question your response would immediately be what api what are the urls what verbs what methods does it support how does the data structures look like give me some documentation writer that would be probably your response and this is exactly where swagger lives swagger is a formal specification standard for describing what a server is able to do swaggers say you know what swag is you can you can do your own picture search in google for the word swag it's like being proud and standing here and saying hey see what i can do this is what i offer you and this is what swagger is all about well swagger is a very informal name so when banks and insurance companies started using web apis they needed a more more senior more more a less funny name as swagger and therefore they came up with the formal name open api specification but essentially if you hear oas open api specification and swagger it's all the same yeah so you can use the word swagger or you can use oas just as you like if you want to read the entire specification you can go to swag or io go to resources open api specification and then please go to open api specification 3.0 we are going to use the latest version of oas in this course so 3.0 and then you have a long long long long long long document what you can do with oas i do not expect you to read the entire specification and to know it by heart of course not i will show you in this in this lesson the most important concepts of an open api specification but believe me if you work in practice if you are going to be a professional developer for microservices distributed systems and so on you will probably have to at one point in time read this documentation the specification to understand all the features of oas because it is super relevant and very very important i don't know a single company out there building web apis who do not who does not use the open a specification in one or another way now how can we write such open api specifications we go to tools and here you find a nice tool which is called the swagger editor this is a nice tool which you can use for simple use cases if you just want to type in some swagger code you can go to download you can try it in the cloud or you can just click on live demo you see that one and this is the one that we are going to use in this course mainly so click on live demo and that will bring you to editor.swagger.io and in this editor.swagger we are going to design our upcoming api okay here on the left hand side you can enter the swagger file and on the right hand side you see the human readable documentation that is auto-generated from your swagger code okay this is your page this is the generated documentation in practice every api project starts with writing or should start with writing such a specification document somebody sits down and thinks hard about what should my api do somebody writes this document by hand and this is then your specification as a developer and you have to build the code in c-sharp in javascript in typescript in go in java whatever you have to write the code that implements the specification written here in swagger okay this is the ideal workflow for building an http based web api to be honest for a simple api projects if you are very very experienced sometimes you skip the step of writing such a specification because you you write the specification in your mind you just know what you are doing but if you are new to apis it's a very good thing to start really not writing code but first specifying what the api is all about in such a file and this is what we are going to do if you already have some code here on the left hand side i ask you to delete everything to start from a blank page i will zoom in a little bit so that you can read my text properly it would be good if you follow along now so um i would encourage you to open editor.swagger.io and try to follow along by typing in the code that i type in if you prefer just focusing on what i show you it's not absolutely necessary that you follow along but i would encourage you to do that i think it's uh it's it sticks better in your mind if you type in the code yourself but at the end of the day it's up to you whether you want to just watch or whether you want to type the first line in a swagger file is always the same it's open api and then you specify the version of the open api specification that we are going to use and the latest version is 303 that's the latest version of the open api specification okay good then we can start implementing or designing the api there are two options here either you know by heart what the swagger specification is all about and you know that for instance there is an info block and then there is a server's block and then there is a paths block it might happen that you know that by heart but to be honest if you are a beginner you probably don't know the swagger specification from the top of your mind therefore you have this nice little cool tool here insert with which you can generate some of the most important aspects of your swagger file so let's go to add info that will add the first basic information block about my api i thought about what we what we should generate and maybe huh maybe at some point in time corona will be over and we are going to do events again maybe parties or maybe some trainings or whatever so therefore we are going to design a very simple event management api so the title will be event management this is a web api for maintaining a list of events you can specify a version this will be the first version of my api and if we want we can add a terms of service document which is just an end user license agreement if you want we can also skip that one we can add a license for the api which might be an open source license for instance and we could add some contact information if somebody should be able to contact us in case of questions it's not that important we just accept that one click on ok and here you see this is the first block it's a basic block about information what is this api all about and if you take a look here on the left hand side this is the header block which just tells the user a little bit a little bit general information about our api the next thing that we could add is the servers block the server's block can also be generated here at servers and here we can specify an url of a server that implements this api this is optional you don't absolutely need to add the server's block because this only is there for interactively trying the api directly in the documentation so if you haven't implemented the api yet just leave out the service block the service block can be added later on once you have once you are done with implementing your api uh did i hear somebody turning on the mic do you have any questions okay not good the next block which is really important is the paths block we have to type in paths by hand and here we can specify the as the name suggests paths so the thing that comes after the server name api.myserver.com slash api slash something okay this is what we can specify and in our case we are going to implement an event management so i think one of the most important parts might be slash events here we are going to design all our operations which relate to events add an event delete an event get all events get a specific events all this stuff and in real world you really sit down and think hard about how you design the paths in our situation it's very simple because we just have events but in a real world api you might have dozens hundreds of different entities that you want to maintain think of sap think of crm systems think of other large order management systems they have dozens and hundreds of these paths and sometimes it's really not simple to come up with meaningful names and a meaningful structure of the paths in real world designing such paths designing the structure of the api is really something that is not trivial in our case we're just learning here so it's very simple and very obvious we want to add events now we can add the first very simple operation get all events of course we are going to use http get because we want to read events so we can now either manually type in the specification of the api or if you click here we can add an operation interactively so here you can go to add operation select the event and then we have a nice little gui here with which we can type in all the things which are relevant for our operation that we want to design in our case we are going to say get because we want to read information let's add a short summary returns all events yes you go to you have to add these two things here and then you go to insert operation okay you select events you select get and then we specify a short summary returns all events we can add a description if we want for instance we can say i don't know return a list of all events in the database okay now check that one out isn't that great we can use markdown for the documentation so what we can for instance do we can say star star star star to write something in bold you can add links and things like that so you can really use markdown the markdown you might be you might be used to from discord or github and so on the last thing which is important is the operation id it's a technical identifier for the operation let's call it get all events we can add some tags here at the bottom here if we want tags are used to structure all your operations and this operation is related to events so i'm get i'm adding a tag which is called events if we for instance add additional operations for managing attendees then we can add the tag attendees for all the apis related to attendees and then it will structure my visual documentation in a very nice way by taking the tags as a kind of headers okay add operation and here you see i have to uh decrease the font size a little bit otherwise i can't meaningfully show you what is generated here on the left hand side you now see the specification of our event and on the right hand side you immediately a human readable documentation that already says returns all events you see the bold text so markdown was correctly interpreted you see we don't have any response codes we don't have any parameters yet of course we have to add now more details to our event but generally we have already specified our first api operation nice good now we can add a bunch of things here and those things are pretty important when you do real world api design some of the things that i'm going to show you now are not available through the gui so here but some of them are so for instance let's add external let's add external documentation just as an example if you do that you can add here a url http docs.myserver.com api and a description read more in my great api docs it's just an example okay so if we add external documentation here now we have the external documentation and if we want to have this external docs not on a global level now we have here a global documentation but if we want to have the external docs specific for this get all events all we have to do is to move it here intended a little bit and here you see now we have the documentation here related to my documentation of this specific operation so it depends it's a waml file so therefore the indentation depends on where you want to add the external documentation to good nice the next thing that i would like to um to show you is how we specify a parameter okay we can't do that but we will not do that through the gui and to be honest i don't know whether you can do it here i can't read it i typically do the parameter definition by hand so please follow me i will just type in the code directly here on the left hand side because what we are now going to do is we are going to define a common schema what is a schema a schema is a data definition a data structure and we can define the data structure and then use it in our api definition because we are now going to define what is an api event all about it can have an id it can have a description it might have i don't know a date it might have a url with some specific information about that event and this kind of data structure this kind of schema is the next thing which we are going to write and this is done in the components section the components are things where we specify set on a central location data structures which are then referenced from our operations okay so we are going to define schemas components schemas now let's define an event schema the event is a type object this object has some properties a property could be for instance date it's the date of the event a property has a type unfortunately json we are going to use json in the web api doesn't have a date data type so a date is represented by a string but we can still document that the string has to adhere to the format date time and we can also add a description date of the event now you might ask yourself how does mrs tropic know all these things how why does he know what's available here so first i am cheating a little bit i have of course in preparation for this lesson i have thought about what i want to do with you so i have my course notes on the different on the second monitor because to be honest i don't know all these things by heart but what do i do in real world if i don't know them by heart well i go to swagger.io i open maybe on the second monitor the open api specification and if i go here to specification then we can take a look here in schema and guess what see components here schemas see schema object and yeah if we take a look at it see all the things that i'm currently using and if i scroll down a little bit you will see oh the yeah now it's okay you will see examples here see that so all i did in preparation for this lesson is i took a look at the specification and i remembered how to define an object by taking a look here at the documentation but i spare you this uh this step because i have already prepared it but i wanted to show you where you can get the documentation from when you want to know what's possible inside of these files okay once you get used to writing these things you know some of the things by heart i would probably have been able to specify all that things just from the top of my mind because i've written so many swagger files in my career but all the details whether this is called date time or date dash time i don't know that by heart i often have to look it up in the documentation but this is what documentation is all about now let's add the next property location it's again type string this time it's just a string what we can do is we can say this is a min length for instance we can specify that 10 with it has a max length length let's say 250 and then we can say a description it is the location of the event of course i think you can imagine that we have to that we are able to add more and more and more properties the only property that i really would like to add here to this object is the id property i will put it here at the beginning it's of type string it could also be an an intel let's use an integer okay let's use an integer it's better let's use an integer the format could be this is an integer 32 we can specify a minimum if we want for instance one and the description would be primary key for events now we have a nice data structure and if we take a look in the human readable documentation you can see all the details so somebody who uses our api will immediately understand what an event is all about and which information has to be passed in if for instance the person would like to create an event so here we have schemas if you want to add additional things then we could add here now attendees and then we add properties and things like that we will not do that yet but i think you get the idea how this is done good this is an event one thing is also important we can specify here not just the type but we can also specify required fields we can say for instance here that the require that the id is required it must not be empty maybe we can also say that date is also required because that makes sense the location is not mandatory it's optional so required is another important thing that we can specify and if we take a look here now these two things are marked with an asterisk so yeah they are mandatory good good good with that we can now go up again to our events get and specify that this event requires a parameter to be passed into this operation get we can say we need a parameter oh sorry we don't have uh get return something yeah forget what i said we don't need a parameter we want to return something okay so what we really want to add here here we want to add responses now the first inside of these repo responses is the response status code what would be a meaningful response status code for a get event operation 400 300 500 200 201 okay 200 exactly so what we can specify here we can say we have a response 200 and then we can say a description uh success for instance and the content will be application slash oh i just recognized that responses was auto-generated up here i'm very sorry i didn't see that so just delete the auto-generated responses here i'm sorry application slash json is the format that we want to respond and which kind of json we specify a schema the type is an array because we return multiple events and the array items have a reference to components schemas event so we have a reference we have a reference here for the get events we return an array of oops this data type another possibility would be that something bad happens 500 description internal server error and we don't specify anything else because if something with 500 exists we don't know yet what we want to respond and if we take a look here on the right hand side you will now see here that the response code 200 success will return application slash json and it will return an array of event objects which contain a numeric id at date and the location in form of a string so you see now if somebody asks you what can this great api do for me the answer is that here on the right hand side and this is generated from this code here on the left hand side now do you think it's a lot of fun writing all these things well not really but it's necessary and it pays off and now you might have the impression that knowing all these things by heart is somewhat difficult but hey it's the same with c-sharp isn't it you have to know that there is a for loop you have to know that there is an if statement you have to know that an asynchronous method starts with async you have to know so many things but for the programming languages that you are used to it just comes naturally to you so this is just a new language and therefore at the beginning it's somewhat overwhelming and somewhat confusing but believe me if you work a lot in the area of specifying apis this is your daily business and it will be so easy to read and so easy to write do you absolutely have to use the editor here no it's just a text file of course you can use visual studio code if you want there are plugins for swagger in visual studio code so you can have exactly the same environment with a nice visual studio code editor here and even show the generated documentation here on the right hand side everything can be done within visual studio code if you want and there are many many other tools with which you can define open api specifications but let me ask you now do you understand now the general principle of defining an api with swagger do you have questions at that point in time clear so far nice very good good so let's stop here let's stop here by adding and writing the swagger documents manually i would like to give you the uh classroom link for today's uh exercise and homework and i ask you to generate to clone the exercise because there is a swagger file in the exercise and we can take a look at it together and try to read it it doesn't make sense that we now spend another hour or so typing in this code it's way more important that you understand the general concept because you have to use it and you have to practice that in your own projects there it makes very much sense so let me quickly get the classroom link for you give me a sec i have to look it up this is the classroom link i will also paste it now in the teams meeting you can either type it in or just click on the link which i just posted in teams i will also post it in discord okay i will also post it in discord now you have it in teams you have it in discord and you have it on the screen so choose whatever's whatever works best for you and i will open the specification here while you are cloning your github classroom here we see the swagger file what i'm going to do now is i'm going to copy the entire swagger file here copy it and paste it in my swagger editor so that i see whether i messed something up but it looks pretty good because i don't see any warnings or errors here and you see that this api is a little bit more complete it's about maintaining an address book a list of contacts this is what you have to implement for your exercise today or for your homework but let's take a look at the structure of the swagger file first so you can either do exactly what i showed you now take a look at the swagger.waml file inside of the github repository that you just created by copying or by subscribing to my classroom link or you can just take a look at my screen here you see in that case we have a single api endpoint here which is called contact but now we have multiple operations here you see the get the post operation and we all yeah question oh really did it stop okay okay i will i will yeah or i will quickly stop screen sharing and re-share my screen maybe it's a problem on my site but i'm still sharing but maybe it's a hiccup so i stop screen sharing now and i start sharing again okay very good so you see here we have the get operation i can fold it here here we have the post operation i can fold it here and then we have a different path if you take a look here with a variable in it and we have a delete operation we also have an operation with which we can find a contact by name this is that one with get and down here we have the schema of the contact okay now let's take a look at the different operations the first one the get one is pretty simple it's just an operation which returns status code 200 json array of the person this is what we did together very simple now the post operation is a little bit more complicated because here you see we specify a request body where we say we expect in the request body a json representation of the person to add this request body is mandatory it's required and guess what we now do not return a 200 status code but we generate a 201 status code which is called created we return the inserted person and we also set a response header which is called location with the url where the event can be queried after it has been created so this is how you specify a response header in a swagger specification the next one is a different path here you see it here we have a path which also contains context but it has an additional id here so this is where we specify the id in the path and here you see the parameter and this parameter here relates oops relates to this path this part of the path you see this is a path parameter and we can specify that the person id has to be an integer value if everything is fine we return 204 no data after it has been deleted no data is fine if the id is not an integer value we specify 400 bad request if the id is a correct number but there is no person with this id we return 404 not found these are the status codes that we talked about in the first hour last but not least i modeled here at different endpoint which is called find by name we could have also combined that with the get up here but i wanted to do it in this way because then i can show you some additional things in asp.net core and here we have a different kind of parameter we have a query parameter so in this case we are going to use api contacts find by name question mark name filter equals to foo so this is the name filter and this name filter is going here oops ah i think you get that if everything is okay with 200 we return an array of people whose name contains this name filter and if we we respond with 400 if there is no name given so if the name is empty then we return a 400 bad request do you get the idea do you understand what the value is of this kind of specification in this case in this homework i want you to write in asp.net a web api now i could have written down in plain english or german as specification but that is not as formal and exact as i want it to be if i give you that specification then you know as a developer exactly what you have to do you have all the information to start coding and that's the idea of writing such specifications ahead of writing code you it forces you to sit down and think hard about how you structure your api about the parameters about the data structures and only if you have at least a rough idea how you how your api should look like then and only then you start coding otherwise you start coding and in the middle of the coding work you recognize that maybe you have a logical mistake in your concept and you have to start over again and again and again and again for such tasks it's much easier to force you to first think at least a little bit about the concepts that you want to embed in your api and then when you have a clear picture in your mind then you start coding don't get me wrong i'm not saying that you have to specify that you have to build a perfect specification before you are allowed to write a single line of code that would not be agile development we want to stay agile but even if we are agile we have to spend a little bit of planning up front to get a kind of mental picture a kind of mental modal about what we want to do it's just like you want to go from your hometown to vienna of course you can be agile you can not think about how to get to vienna and just leave the house and start walking and maybe at some point in time you meet somebody and ask somebody hey am i on the right track to vienna and maybe you just spent hours walking in the wrong direction so a little bit of planning up front is absolutely necessary you don't have to have an exact plan about everything but it is necessary to do a little bit of planning even when you do agile development okay this was the second lesson of our uh lesson today in the first lesson we repeated some concepts about http about status codes about queries about cookies and things like that you heard me messing up with um with some tales i i switched the road caption with hansel and cradle that was the first hour and now in the second hour you learn about swagger and open api specification you learn the concepts of these specifications and we took a look at a granted simple example but still a practical example which will be relevant for your exercise today so with this we spent another hour and it's time to do another break okay uh we spent now i don't know 40 45 minutes i think it's a good idea to have a short break because now we will again switch gears and dive into our third hour and the third hour will be writing code in asp.net core we are going to start with implementing a very simple api and i'm going to show you things which you haven't learned until now about how to use asp.net core and when we have done that you can spend the rest of today's lesson working on this example which you just cloned from the github classroom so now it's 9 57 let's say 10 let's make a 10 minute break so at 10 minutes after 10 we will meet again and dive into asp.net core see you in 10 minutes
Info
Channel: Rainer Stropek
Views: 2,245
Rating: undefined out of 5
Keywords: C#, CSharp, ASP.NET, ASP.NET Core, Swagger, OpenAPI Specification, OAS, REST, Web API, HTTP, HTL Leonding
Id: l-6cNIVMk6Q
Channel Id: undefined
Length: 41min 31sec (2491 seconds)
Published: Thu Jan 21 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.