HttpClient in Asp.Net Core Web API | HttpClient C#

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi everyone in this video I will talk about one fundamental but very important concept for net core developers if you are working with ASP net core then there will be different situations to call the API or the endpoint from your application and this could be calling your own API that you have created or this could be calling some external apis for example you may have to work with how to call the GitHub apis or how to call the Google apis or how to call the YouTube apis this concept that I will talk about in this video will be applicable for all type of scenarios and this is going to be the latest and the most recommended way to deal with the endpoint in your ASP net cor application and this concept is called as HTTP client there are different ways to use the HTTP client in esp. netor application and in this video I will talk about all of them these different ways of using the HTTP client can be implemented based on different scenarios and I will talk about all these scenarios in this video at the end of this video I will also talk about some common scenarios that we always need to perform while dealing with the HTTP client for example you may have to implement the loging for HTTP client at a centralized Place another example could be that you will have to send some common headers in all the requests then instead of writing these headers at all the calls what is the best way to write them at a centralized place if I talk about another example let's say you are working with the Azure functions and if you are calling the Azure function by using the HTTP request then you'll have to pass a key in the URL how to pass that key at a centralized place by using the http client that we will learn in this video let's start this learning to learn more about this concept of calling the endpoints from your net core application I will create an asp net core web API application and whatever concept I will write over there everything will be applicable in all the net core Frameworks so let's start here I can create a new project by clicking on this file button new and choose this project you can also use this control shift n and over here you can choose any net core application for the Simplicity of this video I will be using this ASP net core web API let's click on the next button and over here we have to provide a name this is the name of my application and let's click on this next button over here I have to choose the framework this is the latest net 8 so I will be using this one and here is the authentication type let's leave it none and these are some basic configurations that I have enable open API support do not use top level statements and use controller this concept is also applicable on minimal apis but for this video let's use this controllers click on this create button and this will create a new empty application this is our brand new ASP net core application and now let's see what API I want to call from this particular application so here is my Postman and in this Postman you will see that I'm having this public API so this API will return a list of all the universities from a specific country so for example if I want to search for this India so over here in the qu string I have to pass some value and I am passing India over here let's click on this send button and you will see that we will get a response and here is a list of all the universities in India you can also test it for example here I'm writing this Japan click on this send button and you will see we are getting a list of all the universities from Japan so this is a third party public API and I will be using this API in this demo to deal with this concept first let's create a controller and over here we don't need this weather forecast controller let's leave it as it is let's get a new controller and this is going to be API and let's say universities click on this add button and this will create an empty controller over here and over here let's get our first xtion method and let's use some verbs over here so this is going to be HTTP get and let's use the routing so this is going to be the MP routing now I have to call that API from this acction method and for that I can use the HTTP client so here I'm using that HTTP client like this and and in this client I can set couple of basic things for example here I'm setting this Base address what is the base address for this endpoint The Base address is this particular part let's copy it go back to this file and here we are now this Base address supports only the URI so here we have to use the new URI like this and this URI is expecting an Str string so this is how we can do that now we are ready to call our API and we can do that easily by using this we response is equals to by using this client we can call some methods so here are some methods which is get asnc if the method of your this API is get then you can use get async over here if it is post then you can also use the post async over here similarly we will have all the methods for example this put async and we also have this delete async so let's start this learning from our get async and this get async method we have to provide the request URL so whatever remaining URL we have so for example this one we have to pass it over here like this now at this line we will make a call to this end point and because this is an Asing method so let's use this await keyword and here we have to check if the response of this API is Success then we will do our job over here otherwise we will return a bad request kind of response so what I can do over here where result is equals to let's use this response do content so what I'm doing over here I am basically reading the response that I will get in this particular API and let's use that read as stream async this one and again this is an async method so I have to use this await keyword all right now let's use the return okay method and this okay is again coming from this as. net cor web API and over here I will WR this result and if this property is not true it means there is some problem so here I will return the bad request like this we are done with the changes now let's just run this application and see what is the output this is this s and this is our first AP let's click on this try it out button and click on this execute here you will see that we are getting the response of this particular API here you will notice something very strange it is saying unrecognized response type displaying content as text it means this API does not know what is the response type of that API and because of that it is displaying this content as the text why is this happening this is because over here we are reading this data in form of read as stream Asing we will fix this part in just a bit but this is the first way of how to call the Endo from your esp. net core application and remember over here we are passing this value as an hardcoded value you can also get it from the query or basically from the route let's say this is going to be country and over here let's use this dollar symbol and let's pass this country like like this perfect now here we have to pass the country as well let's run this application again and see what is the output let's pass this Japan click on this execute button and you will see we are getting the list over here for the Simplicity let's try one country which is Bhutan and click on this execute and this time you will see that we are getting only one University over here so this concept is working fine okay so here are some more it is not always required to set this base URL over here you can also set it directly in your get async method like this and you don't have to worry about this Base address this concept will still work now it is up to you now let's talk about our second concept so let's just copy this code and just paste it again over here and here I will be using this V2 let's update some URLs because this is going to be our V1 and this is let's say it is also V1 one as for this new way I will not use this HTTP client like this I will not create the instance by using this new keyword rather I will prefer to use or inject this HTTP client in our program.cs file so for that let's open this program. CS file and over here what I will do Builder do services do add HTTP client that's it now by using this concept we have enabled the HTTP client in this application and now I can use the dependency injections over here so let's use the Constructor dependenc injection and for that I will be using this here I have to use this IH HTTP client Factory let's just remove this concept from here and over here first of all we have to create the request message and we can do that easily by using this where HTTP request message and there is a class new HTTP request message we have to use this class in this class we have to provide what is the method of our endpoint so let's assume that this is HTTP get and we also have to provide our request URL so let's just copy this entire URL let's just paste it like this now we have to create the HTTP client and we can do that easily by using this HTTP Factory so let's say it is HTTP client and by using the HTTP client Factory that we have injected in the Constructor we can create the new instance of our client so we can use this create client like this and now by using this HTTP client we can make the go to our API so here I'm writing this where response is equals to this HTTP client do send async and in the send async method I can basically pass this message and again this is an async method so I have to use the await keyword over here there we go we are done with the changes and now let's just test it we are having this V1 and we are having this V2 let's try this V1 also so here I'm passing this India click on this execute you will see we are getting the response now let's talk about the second one and this is our second API try it out let's pass China and before that let's put a breakpoint over here click on this execute button okay so here we are let's click continue you will see we are getting the request message over here and we are getting the HTTP Cent at this place if I click on this continue button then you will see we are getting the actual response at this place the status code is 200 it means it is fine and this is the is success status code that is the property that we are using now if this is fine now let's click on this continue button and you will see we are getting the list of all the universities from China at this place this is our second way to call the endpoint from our ASP netore application now let's talk about the third one and for that let's just copy this entire code and paste it again and let's just write the V3 over here and here again I'll be using this V3 so as for this third approach what I will be using I will be using some named client over here if you have noticed we are having one problem and this problem is here you will notice that we are passing this entire URL in this request or in case if you have to send some default headers in your request then we also have to Define all of them over here you can remove that easily by using the named client and for the named client let's go back to the program.cs class and over here we have to provide a name to our sttb client for example here I'm writing this universities you can give any meaningful name over here to create this HTTP client and now you can configure some default things over here how so basically I'm setting this Base address over here and this Base address is this particular part let's just cut it go back over here and again I will be using that new URI concept this one in case you have to set some default headers as well so you can also do that easily by using this x do default request headers and over here you will use this dictionary and in this dictionary basically you will set all your default headers but the request that I'm using right now does not require any kind of header so I will not use this one and now what I can do I can basically remove this entire thing like this and over here I just have to provide the name of my this client like this all right now Now by using this concept I can call another method which is get asnc and in this get asnc method I have to provide the remaining URL the remaining URL is this search and the country now this is looking good and it is extremely simple what we are doing we are basically injecting the httv client in our program. CS class over here by using this line and we are are setting the default setting for this API The Base address we are setting over here by using the dependency injection we are using this ihtp Cent Factory in the controller of this particular file and by using this HTTP client Factory I can create this new client like this now we are done with the changes let's just run this application so here is the third one let's click on this try it out button execute before that we have to pass some value so for example this time I will be using Singapore and click on this execute button and here you will notice that we are getting the entire data all right now let's talk about our next approach as of now what we have done we have basically injected this HTTP client over here by giving this name and this is the Base address now there is another requirement and as for that requirement I have to call one more API and for this the Base address is different if I click on the S button then you will see that this is the response of this API I want to call this API also how can I do that remember if I will be using this concept then I will get this Base address for the API but I do not want to do that so for that what I will do I will basically create one more HTTP client over here like this and here I will give a different name let's say it is J and this time the Base address is different what is the base address this is the Base address let's just paste it over here now the concept is that if you need to use multiple HTTP cents in your application then you are free to use you just have to give a name over here and all the default setting of that particular API you can set over here for example this is the Base address for this type then I have written that over here in case you need to pass some headers specific to this particular API then you can set all of them at this place all right now I will be creating my HTTP client by using this J and let's use this let's just copy it and go back over here create one more and and let's use the jokes this time I don't need these parameter remove this also and just write it like this so jokes and what is the remaining URL the remaining URL is this random choke all right we are done with the changes so what we are doing basically in our same file we are calling two apis with different Base address now let's run this application here we are click on this try it out click on this execute and let's see what is the response here you will see that we are getting the response and this is the response of that API now let's deal with this problem here we are getting this data as a text what if I want to get it as the Json how to do that so for that I will be using a type over here so this is the Json file let's just copy it go back to our application and over here let's create a new class so this is going to be add new item let's say joke response and let's just use this Visual Studio feature go to edit paste special paste Jon as the class so this is the class and let's just move it over here all the properties like this all right now I will be using this class to read this jokes and let's just update this name also because it is not looking good get jcks so as of now you notice that we are reading this data as the stream but this time I will be using this data as the read from Json and over here I will have to provide this class name now you will notice that we are reading this data in form of Json let's run this application and test it again here we are having the Swagger this is the API click on this try it out execute and this time you will notice that we are having a proper formatted message and this is the response body and this is our response header so it is application Json and because of that we are getting this formatted data so this is how you can read your response in form of Json now let's talk about our next approach so we are having this V3 and this time let's just copy it or let's go with this one let's just copy it and paste it again and here let's use this J and basically the V1 get jokes let's say it is V1 so here you will notice that first we are creating the client then we are calling this API and then we are using this method to read the data from this Json instead of that we can also call a method directly over here what I can do we can use another method which is get from Json async over here we were using this read from Json async but this time I'm using this get from Json async let's just copy it and paste it over here like this and now I don't have to worry about anything else like this let's use this okay method and in this okay I will be using this response let's see what is the difference over here for that let's over the mouse over here on this response this time you will notice that we are having this HTTP response message and over here you will see that this is the actual response that we are expecting from this API so what will happen over here this HTTP client will call this particular API and it will also map the response in this joke response custom class and that is the type that we will get in this variable and this is something we are returning over here now you will see that we are getting this output in just two lines let's just run this application and see if it is working fine or not this is our new endpoint try it out let's put a break point just for the verification and here we are let's click on this execute button and you will see that we are getting the response at this place click on this continue button and we are getting the output at this place so this is also a way that you can use in your application there is one more approach and this is going to be very important as of now you will see that we are using both our STP clients in this same file for example if I want to create a separate file for the jokes and a separate one for this universities then how to do that so basically I want to create a separate service file for this jokes let's do that so add new item and let's call it joke service add and over here let's get one method so this is going to be public and I want to return something over here so as per this concept I will be using this HTTP client HTTP client this one and let's use this HTTP client over here get from Json async and let's use our type so basically whatever code I have written over here we can use that code directly over there this one and again this is an Asing method so let's use the await keyword and let's just return it from here and we are getting a warning it is saying that it could return some null values so just to avoid it let's use the question mark at this place now we are done with the changes in this joke service now let's make some change in our program.cs class so this time I will be using another approach of including this HTTP client and this time I will provide the name of my service over here J service program.cs class let's just use it and we don't have to provide this key this time we are providing the class name and this HTTP client will be using this name as a separate key now we can use this joke Service as a dependency injection and let's get a separate controller for the testing controller API add let's use this jokes and over here I will be injecting that joke service let's create our first method so this is going to be and let's use this okay method to return the value so this is okay await the service name is this joke service dot get joke async all right and let's give the proper verb so this is HTTP get and let's use the route over here and we are done with the changes now let's just run this application and see what is the output and here you will see that this is our new controller let's click over here try it out execute and you will see we are getting a proper formatted response at this place if you want to test it then you can put a debugger over here and let's put one more tager at this place also click on this execute button again so here we are click on this continue button you will see that we are getting the response from this choke service continue and here we are and this is the most popular way to use the HTTP client in your esp. net core application now these were five ways to use the HTTP client in your net core application now let's talk about one very important situation and the situation is what will happen or how you will handle if you have to make some common changes or some common operations in your sttp client calls for example I have a situation that I want to use the loger at a centralized place can I do that another situation could be that before sending the request I want to make sure that it has a particular header or a particular value another situation could be that I want to append some query string in the URL globally how to do that so for that we have to use some delegate handlers now let's assume for example our want to handle a situation that I need to send a query string parameter in the URL of all the apis how can I do that so for that let's create a new file over here so this is going to be add new item and let's use append query in url Handler you can give any meaningful name over here and we have to inherit it from the delegating Handler this one so this delegating Handler is having a method we have to override that so let's use this override and you will notice that we are having this send Asing method let's override that so in this send Asing method you will see we are having this HTTP request so basically we can modify our request as per the need and this is something that will be called before calling the actual URL so for example here I want to test if the request dot the request URI is not null what does it mean it means we can also provide or set some conditions over here now what I want I want to create a logic over here so this is basically the URL first I'm getting the actual URL from this request request URI this one and then by using this URI Builder I am just creating this URL and by using this HTTP utility class I am setting the quy string so these are my queries and I am basically preparing my URL over here now I can just replace the URL at this place so this is going to be request dot request URI is equals to this new URI and URL that's it now we are done with the changes of this particular class you can write your logic as per the need over here now we have to use this Handler in this application and how to do that so let's go back to this program. CS class again and first of all we have to inject it as the transient how to do that so Builder do services. add Trent like this why we are using it as a trangent this is because this HTTP client that we are using over here is injected as a trangent service in this application and because of that we have to use this add trangent by writing this line we are just adding a dependency we are not using it for example if I want to use it in this joke service so over here I have to use this Dot and there is another method which is at HTTP message Handler this one and I just have to provide the name of this Handler now what will happen all the calls that we are making by using this approach those will come at this place all right so let's put a break point at this place and and we are using this in the joke service so let's go in the joke service and let's we already have a breakpoint over here let's click on this continue button okay so let's just test it again execute and you will see first we are hitting our controller perfect now we are in the joke service click on this continue button and here we are in our Handler all right so if I put a break point over here click on this continue button you will see in the request we are having some values we are appending this query string at this place so this is my query is equals to ni this and you can set any value as per your need click on the continue button and we are getting the response although that query is not required in this API but this is how you can deal with some common operations in your application now for example you are in another situation that you have to set header over here so that is also possible so we are using this request do header do add and you can set your headers at this place so first you have to provide the key and then the value this is how you can set your headers over here now let's assume that you want to include the loging also over here so that is also possible by using the dependency injection here I'm using this I loger and append query let's write it at this place loger or let's not use this underscore so what I'm doing over here basically loger do log information and over here I can just write all my information let's say I want to log only the URL my main purpose of using this ey loer class over here is that we can use the dependency injection in this Handler Let's test it and see if we are getting any error or not here we are click on this try it out execute and you will see there is no problem everything is working fine and we are getting our response on the browser as expected now let's assume that you want to create multiple handlers in your application so that is also totally possible possible you can just register all of them by using this at transend service over here and you can also use the multiple registration over here so for example you can use your second class at this place and third class at this place and by using this approach you can use n number of handers in your specific request that is all in this video I hope the concept of calling the API either external or your internal apis is clear to you now if you are still having any question or doubt then feel free to ask everything in the comment section below if was helpful please like the video and subscribe to the channel thank you for watching have a great day
Info
Channel: Nitish Kaushik
Views: 1,442
Rating: undefined out of 5
Keywords: httpclient in asp.net core, httpclient in asp.net core web api, httpclient c#, httpclient c# web api, httpclient vs httpclientfactory, httpclient post c#, httpclient c# post json data, httpclientfactory, call api from dotnet core, call api from dotnet, call external api from c#, c# httpclient, c# http request, c# http server, c# http, c# http request tutorial, c# httpclient tutorial, c# http post, c# httpclient get request, c# httpclient post request, c# httpwebrequest
Id: 5Hhj2GBMCzs
Channel Id: undefined
Length: 27min 33sec (1653 seconds)
Published: Thu Jan 25 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.