gRPC Service with .NET 7

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
getting a good return on our investment is something that we all look for and so in today's video we explore that concept of maximizing our return by building a full grpc service and then through the use of Json transcoding converting it very quickly and easily into e-rest API [Music] well hello wherever you are whenever you are where am I Melbourne Australia and when is it it's August 2023 so yeah as I said in today's video really we're looking at two things first thing we're going to explore is building a full grpc service so create read update and delete actions as you would typically expect and then the second thing we're really looking at which was a new feature introduced with dotnet7 is something called Json transcoding and what is Json transcoding will in a nutshell it allows us to take grpc service that we build in the first section and annotate those procedures all those methods so that we can use it as a rest based API and you might be going why would we want to do that we've already built grpc service why do we need to convert it to a rest server as well quite simply web-based applications cannot at the moment anyway natively call grpc endpoints there are a couple of ways you can get around that one is by using a proxy which we're not doing today and the other one is to do something like Json transcoding where you going to say convert it into something that can handle native web requests over HTTP one so that's what we're doing today actually I think it's a really interesting feature and hopefully you agree with me on that so as usual code is on GitHub let's not waste any more time and get started so I've just got two slides to go through before we start coding first one is just around grpc what it is and why you would choose to use it so stands for Google remote procedure calls so originally developed by Google but it's now been open sourced and yes it is a remote procedural call framework it uses the HTTP 2 protocol to transport binary messages between endpoints so that makes it super fast it's focused on high performance and chances are if you're using grpc that's the main reason why you chose to use it it relies on something called protocol buffers or protobuf to define the contract between endpoints and in today's video we're going to Define our own protobuf file that contains the contract if you like that will be enforced between the server and the client and it really contains the five method signatures that a client can use to call a server it has multi-language support So a client written in c-sharp can call a service written in Ruby and vice versa but in today's video we're of course building our service in C sharp and the client we're just going to use Postman okay and we'll use Postman to ingest our protobot file so it can see the contract that it can use to call our c-sharp service it's frequently used as a method of service to service communication so you will find it in a microservices architecture for example but from a client perspective specifically a browser-based app I'm thinking in here at the moment those those types of apps cannot natively call egrpc service basically due to the complex use of HTTP too so the way around that would be to use a proxy or as we're going to use today Json transcoding which effectively turns our grpc service into a rest based API that could be used by a web-based application just an important point in that though just because we're using Json transcoding and in effect turning our service into a rest based service that doesn't mean to say that you lose the grpc functionality as well you still have access to that so you effectively have one service and two ways to call it which is actually a very cool feature in my view there's just this quick schematic of what we've already discussed we've got our JavaScript client calling a c-sharp service you can see the Proto buff file exists on both endpoints because we need to define the contract somehow and yeah you can see it's communicating over HTTP too last slide and it's just really to remind you of the ways you can watch my content now and going forward so YouTube of course at YouTube forward slash binary thistle always free for everyone forever but you will have to watch some of the artists alternatively you can check me out over on patreon at patreon.com forward slash binary thistle that's a subscription model so you pay a small monthly subscription you get access to all my videos with no advertisements and then finally there's jackson.net that's a paper video approach so you pay for one video you pay for two videos but you keep them forever there's no subscription and of course no advertisements so with that I think we're ready to start coding so let's get started and scaffold up our grpc servers so as a command prompt let's check to see what version of the.net framework we have installed so that's dot net version and as you can see there I have version 7 installed and if you want to follow along with the Json transcoding element of the video which we'll be doing a bit later you will need version seven as that's when that feature was introduced to the framework okay so next thing I want to do is to change into my working directory and I just happen to have the path if I can type it correctly stored in an environment be able just because it's a rather long and wieldy path uh quick check off uh yep I want to go into the code folder and quick check again yep so I've got some prep code so I actually want to create my project here clear the screen to make it look a bit nicer and it's just a dotnet yeah grpc for the grpc template Dash or and we want to call it to the grpc and that will go away and scaffold that up for us quick directory listing and we'll change into that directory and then we will open it with the vs code which as usual starts on my other screen so I'll pull that on and go to the my command prompt let's make that a bit bigger okay and this is just created a very simple grpc service folders if you get this pop-up just click yes and yeah so we have a very simple grpc service already to find now the first thing I want to do is go into the properties folder come into launch settings Json and we have two profiles here I want to get rid of this HTTP profile so I'm just going to delete that leaving is only https so let's save that off maybe we take that line out it doesn't make any difference functionally but it just looks a bit nicer okay so launch settings Json updated if you take a little tour of our service let's look at the protos folder and what you'll find in here is a protobuf definition okay and it's very simple in this particular case it's just defining a method called say hello and it takes in a hello request message to find down here and it replies with the hello or response more correctly with a Hello reply message defined down here and in both cases each of these messages just has one property name okay a string called name this number here just denotes the position of the property and when we come on to defining our own protobar file in the next section with create and delete methods you'll see some slightly more complex messages and that concept of numbering will embed a bit more okay but in this instance it's really really super simple the other thing to bear in mind about this Proto file is that it's really just a interface definition okay it doesn't actually Implement anything it's really just telling you as a consumer of this service what is available to you so I often think of it just like a c-sharp interface so you define your interface but you actually have to implement the interface somewhere else in code okay so that's how I kind of think all that which brings us nicely on to our services folder and that actually contains the greeter service class which implements the the guitar service so you can see here it actually uses this or Base Class here and here's implementing the actual say hello method that we had defined in our greet Proto file and all it does is it takes in the name from the hello request message and it just responds with that name plus the the word hello okay so it's super simple but it's useful because it gets us to test that everything is working now how does all this work how does defining a Proto file like this how does it allow you to then Implement user base how rare do these classes hello requests come from we're not defining those anywhere or it certainly doesn't appear that we're defining hello request and hello reply anywhere other than in the Greek Proto file and again this is not C sharp code this is just a protobuf file how that actually works is if you come into the Cs project file you can see we have a reference to that protobar file Greek Pro Tool and what happens when you build your project is those classes here the greater Base Class the hello request and the low reply class they actually get built for you okay so it's very important anytime you change your Proto file if you want to have those changes Cascade down into your c-sharp chord you have to rebuild your project in order for those changes to to manifest okay and the way you do that is by linking to it in the Cs project file and then the other thing just to make note of that this is defined as a server rather than a client okay so it's telling us that Yep this is searing up those remote procedure call methods so what I'll do in this section is we'll just quickly run up our service and test it in Postman so control backtick to bring up an integrated terminal and dotnet.net.net run and that should start on two endpoints one for https and one for https I'm just going to copy that and then I'm going to bring Postman onto the screen and just maximize that so I've got collection selected I'm going to select new I'm going to create a grpc request we'll paste in our endpoint but take out the https prefix okay you'll get issues if you don't do that and the other thing that caught me out was you need to enable TLS okay because again we're using a secure endpoint now ideally what you'd like to be able to do now is to select the say hello method from our drop down here but we can't do that because Postman is completely unaware of our grpc service so what we need to do is import the Proto file so it has an idea of the definition of the services that they can call or the endpoints that they can call so click on import a Proto file and I've already kind of navigated previously to my project location I've gone into the protos folder and here is the Greek Proto file and that's just exactly the same file that we have in our vs code project so click on that click open so click next and what I want to do is in the drop down I want to type in the name of this particular service and I've how often they filmed this a little bit a little bit again unintuitive I'm going to call it great and then I'm going to click on that and we'll import it as an API so we now have our protobuf definition within our Postman environment okay and if you come over to apis over here you'll actually see that listed here and you'll see the definitions here okay so that's where that sits within service definitions so now if we click on our down arrow you will see that we have the say hello method okay fantastic and then the only other thing you need to do is Define the message and you just Define that as Json so color brackets double quotes name colon and then I'll be a little bit conceited and I'll use my own name and then if you hit invoke it should respond back with little layers there we go so a very very simple service but it gets us up and running we know it's all working we know postman's working so it means we can move on to the next section so what we'll do now just to finish off our setup let's get rid of the postman for the minute let's kill this for the second let's take that down what we want to do is just add some package dependencies into our project so leaving the to the grpc Cs project file open I'll actually open our Command Prompt back up because we're going to add some packages clear that down let's move this up a little bit and again I'd say there's a million times in my videos the reason I like to have the Cs project file open is so I can see the package references being added you don't need to have it open I just like doing that because I'm weird Okay so the first package we want is dot net ad package and it's Entity framework core we do need the design package but the first one I'm going to add is SQL Lite and as I'm sure as you know that's just a very lightweight SQL database basically it's just a file almost don't need to install anything yeah particularly special to have it working again you can see that package reference has been added clear the screen up key up key and we do actually need the design package as well because we're going to be migrating some stuff in a minute clear that down .net add package and the next one I want is the grpc tools cool and then the last one is dotnet AD package all right asp net core typically Microsoft dot asp.net Court I'm not having a lot of trouble with my spelling today let me try that one more time Microsoft dot asp.net go that's the one it's already stored in the cash so saves me typing it's microsoft.asp netcore.grpc.json transcoding and that's the no surprise of the Json Trend schooling stuff will be doing a little bit later cool so clear the screen get rid of that so what we'll do next is we'll create a very simple model class and we'll use Entity framework core along with the DB context to migrate that uh model down to our sqlite database so we have a persistence layer very simple persistence layer but we'll do that next so back over in our project right click in the file explorer new folder gonna call this models enter models folder I'm going to create a model so new file I'm going to call this two the item.cs we'll include the namespace which is to do grpc dot models and then it's just a public class to the item and a super simple class or just a few properties a little prop tab first one does happen to be an integer and it's going to be our database primary key cool new line plot tab this time it's going to be a string and we'll see it can be nullable and I'm going to call that title excellent two more to go prop tab string again cabin we'll see description and then the last one prop going to be a string call it to to status and this time we will actually assign a value default value of new so the idea is we'll create some to do items and when they get created they will have a status yeah okay fantastic so let's save that off next we want to create a DB context so right click new folder I'm going to call that data enter data folder right click new file and we'll call that app DB context dot CS so very bog standard ASP net core functionality there's nothing too radical in here so namespace to do grpc dot data it's just a public class called appdb context but to implement DB context and we'll need to bring in the namespace so control period to bring in using Microsoft Entity framework core curly brackets and then we'll Define our Constructor so ctur tab at DB context and into this we're going to explain DB context options what's the type the type is DB context I'll call that options and then we'll see that's from the base class so fantastic we'll just leave that empty for now we don't need to put anything in that at the moment or at all in this project anyway and then we just need to Define our data set which is basically our table using our model so let's choose prop tab over what type is it's a type DB set and the DB set is of type to do item and we will need to bring that namespace and let's just finish this first so that's a collection of two new items and I'm going to change this slightly and we'll see that goes to set to the item make sure I spell that correctly and brackets exactly call on and we'll bring in the namespace for our model and as in to the grpc models fantastic let's save that off and then just to wire up our DB context for dependency injection if we come over to the program class I'm going to take out these comments you don't need them take this out as well and we're gonna add a DB context to our service collection so in here Builder access or services collection can add a DB context of what type amp DB context bring in the name space for that and then we'll just configure it so using options opt goes to opt also use SQL Lite I have a tendency to put in two L's there even though that's completely incorrect let's just bringing the name space for that so control period to bring in Microsoft Entity framework core then in here we'll just put in our connection string which is of the format double quotes for the string data source and then we just give it a file name you can call this anything you like someone's going to say to do database not really like a conventional connection string when there's any dramatic security or anything it's really just a file so that should be our DB context wired up so to test that let's generate some migration so control back tick to bring up a command prompt once again and we're going to use the EF core toolset so dotnet EF migrations add and let's just see the initial migration let's generate migrations okay cool we have our migrations folder now as you can see here and if we take a quick look at this it's just fairly simple stuff you can see it's setting up a table name to do items okay and yeah pretty straightforward so we want to migrate that down to our database yet now let me just minimize the stuff what we'll do we'll actually create a database file in our project you can see that's not there yet all we've got is our migrations so we actually want to yeah as I see update our database and you know run our migrations so.net EF database update that looks pretty good and you can see we have our to do database.db file here and then you don't need to do this entirely optional but I like using this tool dbvo just to kind of poke around the database and have a look and see what's happening with it and it's also useful for debugging so I'm going to create a connection to our sqlite database next and then you just specify the file path and yeah that looks like that's pointing to the right location so to do database let's open that up and let's finish that okay and this is the Community Edition I'm using which is free so let's expand this let's explain tables and you can see here there's actually two tables one that Entity framework creates that just has no surprises the migrations history in there and we have one that represents our to-do items okay so we can to a which you have to select the database and do new SQL script and we'll just do a select everything wrong to the items and we'll just run that so it's uh control and enter let me have a table here so an ID title description to the status columns but there's no data in there all right so that brings us to the end of the generic part of the setup we've established our service structure and we've set up our persistence layer next we'll come on and Define our own Proto buff file so let's just minimize deep even come back into our project and get rid of the command prompt and as I said what we're going to do is we're going to Define our own Proto buff file okay so let's right click protos new file and we'll call this to the dot pro tool like so and just before we go on if we come back into the Greek Proto file you can see that we have these three declarations up here I'm just going to copy those because they're pretty much exactly the same so saves me typing and put them into our to do it's also file so syntax is just the version of the syntax being used the next one is the namespace of our application which is fairly straightforward and then we do need to give our package a name so I'm going to call this to do it okay and as per a standard crud Paradigm we're gonna have five endpoints so create endpoints every single item endpoint read the list and point an update endpoint and delete endpoint now these are all going to appear in our service so we have to wrap all of these in the service and by the way these are just comments just place all their comments for for us to manage our project so just bear that in mind so this is all any service so let's wrap it in some curly brackets like that and we do need to give our service a name so to do it okay and just on the kind of syntax highlighting it's actually quite useful you don't get that out the box with vs code like most languages you have to install plugins to get the syntax highlighting so the one I'm using if you come over to extensions is just this one here yes called protobar 3. I'm not any problems with it it seems pretty good you might want to find your own one but I would suggest if you're working with protofiles if you're anything like me you're going to make a lot of some tactical mistakes so syntax highlighting is actually really useful okay so just to recap of specifying our method endpoints in a service but before we do that I want to define the messages that each of these services or each of these endpoints will take and I'm going to do that is just by specifying a message give it a name so let's start with our create endpoint so we'll say create to do and this is the request so what we're passing over curly brackets and then you specify the data type so we're going to pass over the string called title and I'll put that in position one and the other thing will pass over is the description and put that in position two okay and if you come back to our model that should marry up quite closely so again we're not going to pass the ID because the database will take care of that for us when we create it title and description will pass over we're not going to pass over the status when we create a new item because we do that already when we come to doing the update stuff we will allow you to pass the status over at that point okay so fairly simple next one we'll do is the create to the response and I'm just going to return the IDE of the object that was created for that in position one no you could of course specify all the attributes here all the properties here if you wanted to make it a little bit more like rest I'm just going to keep it simple coming back up here let's define our method so RPC give our name create to do what is the exact except I create to-do request and what does it return at the times they create to the response and just a bit of empty curly brackets for the moment that will get populated a bit later when we do the Json transcoding stuff but that's basically our first method defined along with its messages so save that off I'm going to do these next two I'm going to take these next two out the other two I'm just going to cut and paste those in but there's a couple of sort of Novel things in here that I want to go through so let's do our read single stuff so we'll divide it again we'll Define the messages let me just move this up a little bit so message read to to request and we're just going to pass over the ID okay so it's sort of similar to rest in that respect give us a resource here's the ID of the resource that's all we're going to pass over for the response so you read to the spawns we are actually going to return everything so I'm just going to copy this trying to save on typing paste those in here take a new line we're going to return the ID as well so put that in here and we will need to change the attributes for title and description and then we are also going to return the status so it's two status in position four and you'll notice I'm using I think this is called snake case as opposed to I think this is Pascal case and this is snake case so when you're defining protobot files this is how you name your properties okay so you can check out the Google documentation on that as Google actually came up with the grpc spec cool so that's uh which we have to do the method definition so again it's very simple it's very repetitive in fact and we'll see read to do and it accepts a read to do requests and it returns you guessed it you read to the response very very straightforward last one I'm going to type out is the list because there's a little bit of novelty there so like with uh rest Paradigm when you're making a call to a list you can supply some stuff in the query string to maybe filter it but we're not going to do that we're keeping it simple we're just going to see give us all the items that you have and so we're not really passing anything over with it by way of like a parameter or anything like that so I'm a returning of course a list of all our to-do items so we can do a little bit of reuse here we can kind of reuse this message here but you'll see how we do it when we start defining the messages for that endpoint so first one message I'm just going to call it get all request okay and as I say we're not passing anything over so we just Define it as empty in terms of the response I'm going to say get all response and what we're going to do is we're going to make use of this message here maybe do that is by using the repeated keyword okay repeated what are we repeating or repeating the reads to the response call underscore to do I'll put it in the position of one so again making use of this same data we want to turn back but just a list of it so let's specify that method so our PC have a sale list to the what is except get all requests and it returns akl response you're getting it I'm sure you're getting it's not that difficult to be honest with you and again to labor the point this is just an interface spec there's no implementation here so save that off so an interest of time what I'm going to do rather than typing out I'm just going to copy over from my reference project I'm just going to copy over the other messages to support rather to methods so update to the request so passing over the ID because we'll need to actually retrieve an object based on its ID so we can update it the title description and by passing over the to-do status in terms of response we're just passing back the ID and then in terms of our delete we are just passing over an ID and returning the ID of the resource that was deleted let's see if I can format this document no so I just want to tidy up the formatting here that's a little bit annoying so I think it's just these brackets again makes no difference to the code but it would just drive me a bit nutty of if I left it like that okay and last one there and I'm just going to paste in the methods declarations as well so delete and do it the wrong way around and let's do our update here as well okay and these really should be indented as well so that's our Proto file finished for the moment we will come back and revisit it when we do the stuff around Json transcoding just one thing before we move on though before we draw a line under the Proto file if we come back into our CS project file you'll remember we have this directive here linking our great Proto to a project so we do need to do exactly the same thing for Allah to do service so to do Proto and that's it basically it's a server as well okay so when we build our project we will get C sharp classes defined based off of our to do protofile that we can then use when we move on to the next section to Define our service using sharp chord so let's do that now so yeah we want to come on now and create our own service class but just before we do that one step that we need to perform is to build our project and why do we want to build our project well because we've included a reference to our protobot file when we build our project we actually get some c-sharp classes constructed for us and we'll use those classes when we actually come on now to build our own service okay so make sure you do that before you move on so with it they'll successfully we can close that down come over to our services folder right click and file and we'll call this to the service.cs and I'm just going to close down the side panel just to give us a little more room so namespace to the grpc services and then it's just a public class called tude the service and it's going to implement to the it and this Base Class is what we want to implement and again we get this because we have just built our project and just bringing this back up coming over into the to do Proto file just to remind you that's what we call the service here okay cool so curly brackets now we're going to implement our five methods but what those five methods rely upon is access to our database and in order to access our database we need a DB context so we're going to get a DB context through Constructor dependency injection so ctor tab to Define our Constructor and we're going to pass in an app DV context we'll call that DB context let's just bring in the namespace for that and then we're going to assign this value this DB context value to private read-only value called DB context or underscore DB context okay like that and we just need to generate this now as well so control period and it's this one here generate read-only field so if you're a little confused by dependency injection and what I've just done there don't worry you can sign up for a free account onlinejackson.net and take the free dependency injection module that's part of the.net developer toolkit course I have over there and there's a number of other free modules that you can take as well so if you're a bit interested in deep diving the pencil injection yeah you should check that out but hopefully you understand what's going on here because we've registered our DB context and our service collection we can inject it through this Constructor in this particular way excellent so now we're going to do is start defining our methods and the first one I'm going to start with is the ability to create a to-do item so let's get started public override async task what type is the task returning it's returning ecreate to do response and this again is another example of one of those classes that we get because we've built a project and added a reference to our protophile in the project file I'm going to call it creates to do and it accepts or you create to-do request we'll call that request and also accept a server call context and we'll call that context and this just allows us let me just bring in the namespace first control period this just allows us to basically manage our call so you can do things that cancel it and things like that you saw want to but we're not really making use of it today but it is a requirement of the method signature so I want to do a little check on our request object so if request title so that's the title of our to-do item if it's an empty string or likewise with our description then I'm saying that object that's been passed over is effectively invalid and we don't really want to do anything with it so we're just going to throw a new RPC exception and let's define the status of that so a new status codes and I'm going to say invalid argument which I think makes sense and then we can just give that argument something like you must apply a valid object okay so this is somewhat analog just maybe to like a HTTP 400 type response although it's not the same thing exactly it's similar okay so assuming we have a valid object let's actually create one so or to the item so we need to bring in the namespace for our models equals new to the item and let's do that now bring in the namespace so models and we're just going to assign values to this so title equals request title and description and equivalency in there not a assignment so that's better description equals request description now this is a little clunky um actually assigning creating objects in this way I'd probably recommend in a more production type environment you use like a mapping framework something with automaper for example and again over in the.net developer toolkit course I actually do have a module on auto mapper and dtos that goes into this in more detail but again because this is a small object I think it's okay to do in this way so with our object created all we need to do is just add it to our database so we're going to await on our DB context and we're going to add async our to-do item well the other thing I forgot to mention is probably an obvious one we don't Define the state here because we are Auto assigning the status of new and we don't have to Define an ID because the database does that for us so for a creation perspective we just need these two attributes here now again this is standards Entity framework core stuff but if you don't save your changes then the fact that you've added this item to your DB context makes no difference it won't actually get processed down to the data layer so you need to save changes async in order for that to actually happen and then we want to return a result so return task and from result new create to do response and this is just the ID of the new object that we have created so if we make that equal to our to do item id we will have an ID at this point because we've been assigned one by Entity framework or more correctly by our sqlite database and we don't need a semicolon there all right so that is looking pretty good let's save that off and let's run up so.net run actually before we do that I always forget this step just before we do that what we need to do we bring our sidebar backup we come into program class and we actually need to register our service always forget to do that and always get errors so thankfully this time I remembered so in here to the service like that okay that's better so we can now run up and we can make an attempt to call our create endpoint so.net run not Rob one so let's bring Postman up and we're going to make a new request to our create endpoint so new grpc and to enter the URL so just copy up to localhost paste it back in don't forget to enable TLS and then if we come over to our method definitions we can choose to use the Greek definition we created in the introduction or we can import EU file and I'm going to do that so select up to do a Proto file and open that fantastic and click next and type in the name of a new API so I'm going to call this to do service and we'll import that and you see that over here on the API collection and also when we click on our method selection you can see we get all five methods and that's because all five methods are defined in the protofile but they're not all implemented so if we pick one of the unimplemented ones like list to do and invoke it we get an unimplemented result which makes sense so let's pick our create methods and we'll Define a message so let's give it a title and we'll say finish other endpoints and let's just test that without a description we should get an error and we do we get an invalid argument so you must Supply a valid object so that's looking pretty good so if we then Supply a description I need to make sure we spell it correctly or I spell it correctly see remaining four and invoke that you should get an ID back of our resource let me get an ID of one so that's looking pretty good all right so let's move on to our next endpoint so let's come on and introduce another endpoint method so get rid of that to come back into our project into our service class to do service and the one we'll do next is reading a individual to do item so let me just get my cursor in the right place so that's public override async and you'll start to see a pattern emerge here task read to response and we'll call this method read to do let me get rid of this so I get a bit more room and it accepts you read to the request call it request as usual and again accepts a server called context and call that context so I just want to do a little bit of validation I just want to check that the ID is non-zero but it's still not return our response to us but I just want to do that anyway so it's less than or equal to zero because we're not going to get an index from our database that's less than or equal to zero then we're just going to throw an exception so throw new RPC exception and that's a new status code and this is the same one refused before invalid argument and we'll give it something a bit more specific resource index must be greater than zero cool all right so having performed a little bit of validation let's attempt to get an item back from the database so to clear a variable called to do item then await on our DB context to do items collection we'll use first of default and we'll say t goes to T ID equivalent to the request ID that's passed in job oh and I need to use the async method of this that's what I'm waiting on it that's why it's erroring out and that requires Entity framework core or light that's looking pretty good to me so we'll then just do a little check on the to do item to make sure it's not null so if it's not null then we have something and we'll return back with that value from results now I'll create a new to do response and this time we're going to pass back everything so we'll pass back the ID which will be the to do items ID aspect the title and again as I've already mentioned Auto mapper or something like that would be a good tool to use here a good framework to use here as it would save you doing all this sort of manual assignment but this is I think the most properties we're going to be assigning so Four's not too bad but it's on the cusp of what I would say was acceptable before you started using a framework and again I do have a module in the net developer toolkit course that goes through object mapping and data transfer objects cool so that's what we do if it's valid and then if it's not valid then we'll throw a new exception so new I keep wanting to see RCP I have no idea RPC exception and new status and this time the status code we want will be not found so that's again analogous to the HTTP 404 that you would get in a rest based API so we'll just single task with ID and using string interpolation we'll just here's our request again and pass through whatever the ID was okay so first validation check is just checking to see that it's greater than zero the storm will guarantee will get a hit and this one is really just saying yeah you passed in a positive integer but there was no resource fund so we can save that off and let's run up record stop that from running from last time and we'll do a net run fantastic let's bring up Postman and I'm going to drop them and we will get our read to do action and so we'll change our message it's an ID and we'll make that equal to that's an integer so we don't put it in quartz so we'll make it equal to one and we should get back to the object that we've just created that's looking pretty good if we put in zero invalid arguments in the Xmas period and zero so it's looking pretty good now we've put in something that is a valid ID but it doesn't relate to any task we get our could not find the entity response so I think that's looking pretty good so let's move on now I did debate at this point whether to just cut and paste in the remaining actions and for those of you who've watched my other videos you know I never do that and I'm going to hold true to that and I'm not going to cut and paste code so I'm going to type out the remaining three methods as well and if you know that's a bit laborious for you then obviously feel free to fast forward the video the time codes are also in the video uh certainly on YouTube I put the time codes below so you can skip ahead to the next section probably look at the Json transcoding stuff but I'm going to continue with writing the methods out so next one we're going to do is the list methods and to make sure I'm in the right place let me just move my code window up a little bit so again public override async task tons of get all response so we'll call this list to do and it accepts a get all requests call that request and a server call context or context the clearer variable for our response object that we're going to pass back so even if it's null we still want to pass it back so that's just a new get all requests or get all response object we'll populate that a bit later next we want to actually attempt to get the to do items from the database so we'll declare another variable called to do items and we'll make that equal to DB context to do items to list async like that okay now this could be null two new items could have nothing they may not have anything in there so irrespective we're going to look around our collection so create a obstacle to do looking out to do items and then as before we're just going to assign our object manually so we'll say response to do add the new read to the response and we'll put any semicolon there and now might actually copy this code here just to see me typing it because it's a little bit laborious and we need to change this though all right cool and then we just return that and of course this response object get all response could be null or it could have items in it doesn't really matter let me just return the response like so okay save that off leave on our codes Let's test it and Postman so what I might do is I might add another item and we don't really need to to test it but I might just do it anyway so we have a couple in there just so we can see it's iterated in so title is finish update endpoint and description has update in point and we'll involt that go and then if we come down to here and do our list to those we don't need a message so take that out and about that you get our collection of items back so again that's looking pretty good so two more to do let's do our update one next and again these are all just variations on a theme note to be honest with you so let's come over here Let's do an update so public override async task update to the response we'll call this update to do it and it accepts and update to the request hold requests and a server called context called context but should come there's no surprises to you so again as before we'll do a little bit of validation just to make sure that what's been passed through is somewhat relevant so request object looks let's look at ID we'll do the same check that we did in our last end point and just check that the index is not less than or equal to zero and then again I might do a little bit of cutting and pasting from our creating point and just copy this scores as well or these Clauses as well so don't forget to put our R in and we'll do that check okay so we're just checking the ID the title and the description and then again that's the also going to copy and paste code but you've already seen me type this so I think I can give myself a pass on that I'm gonna copy this and see my Supply a valid object as our exception and I keep wanting to type our PC exception as our CP exception for some reason so let's leave it to that so what we're going to attempt to do then is retrieve our object that we want to update we want to retrieve that from the database so let's create an uh placeholder for that and we will wait on our DB context to do items first of default in fact I could copy this as well I might just do that from our read method up here let's copy this because it's pretty much exactly the same I'll keep my code consistent okay so we'll attempt to get our item we'll do a quick check so if the to-do item is null uh you don't have a hit then there's nothing to update so we'll throw a new RPC exception new status and the status code is not found so again make a 404 response and I could have copied that from upstairs as well but let me just type it out so no task with ID it's doing interpolation request a little bit of C sharp not C sharp a little bit of JavaScript kind of creeping in there sort of not quite but sort of okay and that's cool and then this is sort of going to be analogous to a rest based put request where we just update the whole object as opposed to a patch request which patching allows you to update just specific elements in an object to put requests generally updates the whole object we're going to take the put kind of approach and just update everything so again this is something where you would typically use a mapping framework to do this for you and you wouldn't have to do what I'm about to do now which is map everything through so we'll say the title equals the request title whatever the value happens to be in there we'll see the description likewise the request description and this time we're going to allow the status to be updated so the whole point of updating your to-do items is to I guess go through some kind of state transition and say it's no longer new it's in process or it's paused or something canceled so we will allow that was right to pass over the status all we then need to do is just save that back to our DPE using save changes async like so so we've retrieved our object from our context with now updated it we've just saved it okay and then as per our protofile all we want to do is just return the ID of the updated object update to the response and again if you wanted to you could absolutely return the whole object back if you liked entirely up to you can maybe do that offline at some other point so to do the item ID dot ID not comma ID and also my equal sign there okay looking good don't need a semicolon there I keep doing that okay cool so no Summit no semicolon at the end of our assignment there so let's just run up that might run and bring Postman back onto the screen as well and what I'm going to do is I'm going to copy this object here or update endpoint to do item because we have finished it well we're testing it so maybe let's update that to reflect that so over in our drop down let's select our update endpoint let's go to message and let's paste in that object and I'll leave the title description the same but I'm going to put the status as in test okay and let's invoke that we've got an ID back so if we then use our other methods which is our let's just use the list and just bring back everything you can see that we've updated our objects it's now in tests so I think with it being intestinal um a test completed it's looking pretty good so we can see done and we'll just select the right method again let's look it and yeah we are done so all that's left now is our delete endpoint so a last endpoint delete is actually probably the simplest of all of them so you could probably have a crack at writing this yourself but I will just do it anyway because I'm a nice guy alright async task of type delete to the response and we'll call this delete to the and it except to delete to do request we'll call that request server called context called context and we're just taking in an ID so what I might do is for our read one I'm going to do this little bit of checking here to make sure we're passed through our positive integer through an exception if not actually you can probably copy some more stuff from that as well yeah so let's copy this so we're going to attempt to retrieve our item promo database do that as well this is where diverges slightly so if the to do item it's null demo through a new RPC exception new status and this is again sort of not found type status code of not fund can use string interpolation we'll say no task with ID first ID otherwise we've got our valid object so all we want to do is use our DB context and use the remove method and remove our item like that and of course don't forget to save changes save changes async actually in this case and then we did say that we will return the ID of our deleted object so return of eight task from result new ly to the response and we'll just say the ID is equal to do item ID perfect save that off stop that from running and run up once again putting Postman back onto the screen let's list our items we still have two and I'm going to delete this one here number one okay so come down to delete and just update this to number one and I'm gonna bulk it looking good and I'll list them all again and we should only have one item there which is in fact what we have so that really brings us to the end of our section on building our Pure grpc service okay it does a great read update delete operations you could of course make it a bit more detailed and elaborate what we're going to do now though is move on to the section on Json transcoding where we take our Pure grpc service and we allow users to call it from a web endpoint and basically it's going to work effectively like a rest based API so you basically get two for one you'll still have your grpc service that you can call using grpc and HTTP 2 and they'll also have a service that you can call using a web front end so let's start with that so in order to enable Json transcoding within our project we need to first of all add two reference files and those files are listed in this Microsoft document here and so I'll link to this document in today's video as well but if we just scroll down a little bit it's these two files here HTTP Proto and annotations portal okay and if you just follow these links take you to GitHub repository and you have those files here okay so let's do that first of all and that basically just introduces Json transcoding support okay so we're not going to look at those files in any great detail or do anything specifically with them you just need to introduce them to our project so over here in a project you do need to put them in a very specific directory so in the root of your project create a new folder called Google and inside the Google folder beautiful called API and then two new files new file I'm going to call this one annotations dot pro tool and the other one is http portal okay excellent and I'm just going to copy and paste those files from the GitHub repository I just showed you annotations Pro Tool save it and I'm not going to go through this in any detail at all I'm just copying it over and we'll save that off like that next thing you have to do we've already done it actually if you come into a project file is include this package here Microsoft asp.net core grpc transcoding but we did that at the start of our project build so you already have that if you didn't do that though just make sure you have it and we're going to come on and use it now next thing to do then is to come into the program class and where we have our services here and grpc we need to further Define that as using Json transcoding so dot add Json transcoding and that basically means that Json transcoding no surprises is in play now in addition to Classic grpc we'll save that off as well and then really the more interesting thing that's really just a setup that's the wiring up if you like what we then need to do is come into our Proto file or to do a protophile and we need to start annotating each one of our endpoint definitions to tell it essentially how we want it to behave as a HTTP endpoint so let's get started with that so to start annotating our endpoints the first thing we need to do in our protofile is to include a reference to the annotations file we just created in the last section and we do that just by an import statement and providing a path to where we can find that file and that's our annotations dot pro tool and don't forget the semicolon now before we come on to actually doing the annotations the other thing that I forgot to do in the last bit of setup was over in app settings Json I want to change this protocol from just being HTTP 2 to allowing HTTP 2 for our grpc stuff but also allowing the older HTTP protocol so that we can actually use web-based requests and so I'm just going to update this to say HTTP one and HTTP tool so again that's a really important part of this grpc relies upon HTTP 2 for the most part but because we're introducing web-based traffic we need to be able to use HTTP one as well all right so with that little diversion over we can now actually annotate our endpoints first one I'm going to pick is this one here the list to do endpoint so fairly simple one arguably the simplest endpoint we have so inside the curly brackets we come down and we specify an option and we have to do this for every single one of our annotations so it's fairly uninteresting but absolutely critical so it's just Google dot API dot http the real interesting stuff comes next so set of curly brackets semicolon do not forget that semicolon you'll get a compile time error if you leave it out and then we just Define or annotate what this endpoint should do from a HTTP web request perspective and first thing we specify is the build that we want it to respond to so standard rest stuff this is going to be a get based request and when we do our other endpoints you'll see the other verbs that we will bring into play at that point in time but for now let's finish this one off next thing we specify and the last thing we specify in this example anyway is just a route to where this endpoint can be found so forward slash and then it can be really anything you like so I'm going to say V1 for version 1 over API and this can be found at the to-do endpoint another very important point do not forget the forward slash you'll get a compile time error if you leave that out as well so let's save that off and let's run up to taste it so we're getting quite exciting cool let's bring Postman back onto the screen new request HTTP request this time let me just get the end point so this time you do want to include the https prefix unlike the grpc so let's put that in here we already have get request selected by default and we should be able to run this up indeed you do so we now have a HTTP endpoint as well as a grpc endpoint which I actually think I don't know about you I think that is exceedingly cool thing to be able to have I think it's really quite awesome so let's just wrap this up and annotate the rest of our endpoints and we'll do a quick bit of testing so let's just finish off the rest of an annotation so kill down Postman stop this from running and we'll come back into our Pro Tool file so I'm just going to work top to bottom and we'll start with our create to-doing point so as before coming here specify an option and it's just Google .api.htp HTTP and we make that equal to what verb would we expect in a rest API when we're creating a resource that's correct a post request and the route is just going to be exactly the same in fact as our listing requests so V1 to do the only slight difference comma is we want to specify an annotation for the body and here I'm going to use a wild card and see I just want everything for the body pass through to our request I'm not going to test this just yet I'm going to move through the rest of the end points again good idea to have syntax highlighting for protobar files installed because you can see here this doesn't look quite right and that's because I forgot the semicolon here so I do suggest you install some form of syntax highlighting because protobar files can get a little bit tricky especially when you're as bad a typist as I am so next one we're going to do is reading a single line so again option Google API http equals again it's going to be a get request a little bit more interesting this time forward slash V1 forward slash to do but this time we can actually have a variable in here saying that we expect an ID to be passed through in the route and getting standard rest practice don't forget semicolon there our list one has already been defined so we come on to our updates so in here specify an option Google API http equals curly black as I'll put the semicolon in to start with standard rest we're just going to make this a put request and the route is going to be forward slash V1 forward slash to do now in most rest based apis you would probably have an ID in here denoting the resource ID certainly the ones I've seen I'm not doing that today because we're actually getting the ID in the body payload which brings us nicely on to specifying the role for the body in this case and again likewise with create we just want everything passed through cool and then that brings us on to our last annotation delete should be getting the hang of this by now option Google API http equals no surprises delete and then just a route so forward slash V1 forward slash two do and again we are going to expect an ID passthrough in the route like that don't forget to send me cool on okay I think that's everything done we'll find out if we made any mistakes we'll do a.net run looking good and let's come back to postman so let's just create a new HTTP request for our creation endpoint so select post I'm just going to come back here copy this route and paste that in like so and then come over to our body and we will Define our body so it's raw Json and let's create a new to do item so we'll see a title complete testing and let's not pass over the description and see what we get so we get a 404 not a 404 we get 400 bad request which is exactly what we would expect and we get our validation message here which is excellent Okay so let's Rectify that description say all endpoints that should be good enough so click Send excellently getting you to do item created with an ID of five let's come back to grpc Let's uh let's make a call yeah let's list everything that's good enough and we can see that you can use grpc we can use our HTTP stuff and we have our new endpoint here excellent so let's see if we can update this so let's just copy this payload and we'll come back to here let's just update this to be a put request let's change the body payload to something like this and we will see that the testing is now in progress like that hit send we get an ID back let's test the retrieval of our individual endpoint so that was id5 send me get that we get in progress this is looking really good let's pass over an ID that we know we don't have excellent we've got 404 not found and then what's the last one well I think we're basically finished testing we test them all create update list getting individual items all that's left is delete so let's delete this one here update that well again that's working 404 that's cool let's put delete let's put id5 in that's what I'm into doing the first place so cool and let's see if we can pull that back no task with idea five fantastic so that really brings us to the end of the video I don't know about you but I think that's really cool you've got a grpc service that you can use for service to service communication and all the benefits of the speed that come with grpc but you could also expose that service to a web-based client without having to do too much work you saw how easy it was to annotate those grpc endpoints so I've done about you but I actually really really love this feature I think it's great I'm going to use it I know I'm going to use it in my own projects but as usual be really interested to find out if you feel the same way please put your comments in the section below so until the next time I see you and make my next video stay very safe and hopefully see you again very soon thank you [Music] foreign [Music] [Music] [Music] [Music] [Music] [Music] [Music] foreign [Music]
Info
Channel: Les Jackson
Views: 17,864
Rating: undefined out of 5
Keywords:
Id: Rqz9XiSqH3E
Channel Id: undefined
Length: 77min 48sec (4668 seconds)
Published: Wed Aug 02 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.