Web API With HttpClient or Consume Web API From Console Application
In this article, we are going to learn how to call Web API using HttpClient. Normally, we call a Web API either from jQuery Ajax or from Angular JS, right? Recently, I came across a need for calling our Web API from the server side itself. Let me show you how it's done.
Join the DZone community and get the full member experience.
Join For Freein this article, we are going to learn how to call web api using httpclient. normally, we call a web api either from jquery ajax or from angular js , right? recently, i came across a need for calling our web api from the server side itself. here, i am going to use two visual studio applications. one is our normal web api application in which i have a web api controller and actions, while the other is a console application where i consume my web api. sound good?
i am using visual studio 2015. you can check out tips/tricks/blogs about these mentioned technologies from the links given below.
now we will go and create our application. i hope this is helpful.
download the source code
you can always download the source code here.
background
we all use web api in our applications to implement http services. http services are much simpler if we use web api, but, the fact is, the benefits of using web api are not limited to that. previously, we've used wcf services instead of web api, when we were working with endpoints. here, i am going to explain an important feature of web api that allows us to call web api from our server itself instead of using an ajax call. that is pretty cool, right? now, we will create our application.
first, we will create our web api application.
creating web api application
click file-> new-> project then select mvc application. from the following pop up we will select the template as empty and select the core references and folders for mvc.
empty template with mvc and web api folders
once you click ok, a project with an mvc-like folder structure with core references will be created for you.
folder structure and references for empty mvc project
using the code
we will set up our database first so that we can create an entity model for our application later.
create a database
the following query can be used to create a database in your sql server.
use [master]
go
/****** object: database [trialsdb]
create database [trialsdb]
containment = none
on primary
( name = n'trialsdb', filename = n'c:\program files\microsoft sql server\mssql11.mssqlserver\mssql\data\trialsdb.mdf' , size = 3072kb , maxsize = unlimited, filegrowth = 1024kb )
log on
( name = n'trialsdb_log', filename = n'c:\program files\microsoft sql server\mssql11.mssqlserver\mssql\data\trialsdb_log.ldf' , size = 1024kb , maxsize = 2048gb , filegrowth = 10%)
go
alter database [trialsdb] set compatibility_level = 110
go
if (1 = fulltextserviceproperty('isfulltextinstalled'))
begin
exec [trialsdb].[dbo].[sp_fulltext_database] @action = 'enable'
end
go
alter database [trialsdb] set ansi_null_default off
go
alter database [trialsdb] set ansi_nulls off
go
alter database [trialsdb] set ansi_padding off
go
alter database [trialsdb] set ansi_warnings off
go
alter database [trialsdb] set arithabort off
go
alter database [trialsdb] set auto_close off
go
alter database [trialsdb] set auto_create_statistics on
go
alter database [trialsdb] set auto_shrink off
go
alter database [trialsdb] set auto_update_statistics on
go
alter database [trialsdb] set cursor_close_on_commit off
go
alter database [trialsdb] set cursor_default global
go
alter database [trialsdb] set concat_null_yields_null off
go
alter database [trialsdb] set numeric_roundabort off
go
alter database [trialsdb] set quoted_identifier off
go
alter database [trialsdb] set recursive_triggers off
go
alter database [trialsdb] set disable_broker
go
alter database [trialsdb] set auto_update_statistics_async off
go
alter database [trialsdb] set date_correlation_optimization off
go
alter database [trialsdb] set trustworthy off
go
alter database [trialsdb] set allow_snapshot_isolation off
go
alter database [trialsdb] set parameterization simple
go
alter database [trialsdb] set read_committed_snapshot off
go
alter database [trialsdb] set honor_broker_priority off
go
alter database [trialsdb] set recovery full
go
alter database [trialsdb] set multi_user
go
alter database [trialsdb] set page_verify checksum
go
alter database [trialsdb] set db_chaining off
go
alter database [trialsdb] set filestream( non_transacted_access = off )
go
alter database [trialsdb] set target_recovery_time = 0 seconds
go
alter database [trialsdb] set read_write
go
now we will create the table. as of now. i am going to create the table tbltags.
create tables in database
below is the query to create the table tbltags .
use [trialsdb]
go
/****** object: table [dbo].[tbltags] script date: 23-mar-16 5:01:22 pm ******/
set ansi_nulls on
go
set quoted_identifier on
go
create table [dbo].[tbltags](
[tagid] [int] identity(1,1) not null,
[tagname] [nvarchar](50) not null,
[tagdescription] [nvarchar](max) null,
constraint [pk_tbltags] primary key clustered
(
[tagid] asc
)with (pad_index = off, statistics_norecompute = off, ignore_dup_key = off, allow_row_locks = on, allow_page_locks = on) on [primary]
) on [primary] textimage_on [primary]
go
can we insert some data into the tables now?
insert data into table
you can use the below query to insert the data into the table tbltags .
use [trialsdb]
go
insert into [dbo].[tbltags]
([tagname]
,[tagdescription])
values
(<tagname, nvarchar(50),>
,<tagdescription, nvarchar(max),>)
go
next thing we are going to do is create an ado.net entity data model.
create entity data model
right click on your model folder and click new, then select ado.net entity data model. follow the steps given. once you have completed the processes, you can see the edmx file and other files in your model folder. here, i provided dashboard for our entity data model name. now, you can see a file with an edmx extension has been created.
now let's create our web api controller.
create web api controller
to create a web api controller, just right click on your controller folder and click add -> controller -> select web api 2 controller with actions, using entity framework.
web api 2 controller with actions using entity framework
now select tbltag (webapiwithhttpclient.models) as our model class and trialsdbentities (webapiwithhttpclient.models) as data context class. this time we will select to use a controller with async actions.
web api controller with async actions
as you can see, our controller has been given the name of tbltags . here, i am not going to change that... if you wish to change it, you can do that.
now, we will be given the following code in our new web api controller.
using system;
using system.collections.generic;
using system.data;
using system.data.entity;
using system.data.entity.infrastructure;
using system.linq;
using system.net;
using system.net.http;
using system.threading.tasks;
using system.web.http;
using system.web.http.description;
using webapiwithhttpclient.models;
namespace webapiwithhttpclient.controllers
{
public class tbltagscontroller : apicontroller
{
private trialsdbentities db = new trialsdbentities();
// get: api/tbltags
public iqueryable<tbltag> gettbltags()
{
return db.tbltags;
}
// get: api/tbltags/5
[responsetype(typeof(tbltag))]
public async task<ihttpactionresult> gettbltag(int id)
{
tbltag tbltag = await db.tbltags.findasync(id);
if (tbltag == null)
{
return notfound();
}
return ok(tbltag);
}
// put: api/tbltags/5
[responsetype(typeof(void))]
public async task<ihttpactionresult> puttbltag(int id, tbltag tbltag)
{
if (!modelstate.isvalid)
{
return badrequest(modelstate);
}
if (id != tbltag.tagid)
{
return badrequest();
}
db.entry(tbltag).state = entitystate.modified;
try
{
await db.savechangesasync();
}
catch (dbupdateconcurrencyexception)
{
if (!tbltagexists(id))
{
return notfound();
}
else
{
throw;
}
}
return statuscode(httpstatuscode.nocontent);
}
// post: api/tbltags
[responsetype(typeof(tbltag))]
public async task<ihttpactionresult> posttbltag(tbltag tbltag)
{
if (!modelstate.isvalid)
{
return badrequest(modelstate);
}
db.tbltags.add(tbltag);
await db.savechangesasync();
return createdatroute("defaultapi", new { id = tbltag.tagid }, tbltag);
}
// delete: api/tbltags/5
[responsetype(typeof(tbltag))]
public async task<ihttpactionresult> deletetbltag(int id)
{
tbltag tbltag = await db.tbltags.findasync(id);
if (tbltag == null)
{
return notfound();
}
db.tbltags.remove(tbltag);
await db.savechangesasync();
return ok(tbltag);
}
protected override void dispose(bool disposing)
{
if (disposing)
{
db.dispose();
}
base.dispose(disposing);
}
private bool tbltagexists(int id)
{
return db.tbltags.count(e => e.tagid == id) > 0;
}
}
}
as you can see, we have actions for:
so, the coding part to fetch the data from the database is ready, and now we need to check whether or not our web api is ready for action! to check that, you just need to run the url http://localhost:7967/api/tbltags . here tbltags is our web api controller name. i hope you get the data as a result.
web_api_result
as of now, our web api application is ready, and we have just tested whether it is working or not. now we can move on to create a console application where we can consume this web api with the help of httpclient. so, shall we do that?
create console application to consume web api
to create a console application, click file -> new -> click windows -> select console application -> name your application -> ok
console application
i hope now you have a class called program.cs with the below codes.
using system;
using system.collections.generic;
using system.linq;
using system.text;
namespace webapiwithhttpclientconsumer
{
class program
{
static void main(string[] args)
{
}
}
}
now, we will start our coding. let's create a class called tbltag with some properties so that we can use those when necessary.
public class tbltag
{
public int tagid { get; set; }
public string tagname { get; set; }
public string tagdescription { get; set; }
}
to get started using the class httpclient , you must import the namespace as follows.
using system.net.http;
once you have imported the namespaces, we will set our httpclient and the properties as follows.
httpclient cons = new httpclient();
cons.baseaddress = new uri("http://localhost:7967/");
cons.defaultrequestheaders.accept.clear();
cons.defaultrequestheaders.accept.add(new system.net.http.headers.mediatypewithqualityheadervalue("application/json"));
as you can see we are just giving the base address of our api and setting the response header. now, we will create an async action to get the data from our database by calling our web api.
get operation using httpclient
myapiget(cons).wait();
following is the definition of myapiget function.
static async task myapiget(httpclient cons)
{
using (cons)
{
httpresponsemessage res = await cons.getasync("api/tbltags/2");
res.ensuresuccessstatuscode();
if (res.issuccessstatuscode)
{
tbltag tag = await res.content.readasasync<tbltag>();
console.writeline("\n");
console.writeline("---------------------calling get operation------------------------");
console.writeline("\n");
console.writeline("tagid tagname tagdescription");
console.writeline("-----------------------------------------------------------");
console.writeline("{0}\t{1}\t\t{2}", tag.tagid, tag.tagname, tag.tagdescription);
console.readline();
}
}
}
here res.ensuresuccessstatuscode(); ensure that it throws errors if we get any. if you don’t need to throw errors, please remove this line of code. if the async call is a success, the value in issuccessstatuscode will be true.
now when you run the above code, there are chances to get an error as follows.
error cs1061 ‘httpcontent’ does not contain a definition for ‘readasasync’ and no extension method ‘readasasync’ accepting a first argument of type ‘httpcontent’ could be found (are you missing a using directive or an assembly reference?)
this is just because of the readasasync is a part of system.net.http.formatting.dll which we have not added to our application as a reference yet. now, we will do that. sound ok?
just right click on the references and click add reference -> click browse -> search for system.net.http.formatting.dll -> click ok.
add references
please add newtonsoft.json also. now, let's run our project and see our output.
web_api_consumer_get_output
now, shall we create a function for updating the record? yes, we are going to create a function with 'put' request. please copy and paste the preceding code for that.
put operation using httpclient
static async task myapiput(httpclient cons)
{
using (cons)
{
httpresponsemessage res = await cons.getasync("api/tbltags/2");
res.ensuresuccessstatuscode();
if (res.issuccessstatuscode)
{
tbltag tag = await res.content.readasasync<tbltag>();
tag.tagname = "new tag";
res = await cons.putasjsonasync("api/tbltags/2", tag);
console.writeline("\n");
console.writeline("\n");
console.writeline("-----------------------------------------------------------");
console.writeline("------------------calling put operation--------------------");
console.writeline("\n");
console.writeline("\n");
console.writeline("-----------------------------------------------------------");
console.writeline("tagid tagname tagdescription");
console.writeline("-----------------------------------------------------------");
console.writeline("{0}\t{1}\t\t{2}", tag.tagid, tag.tagname, tag.tagdescription);
console.writeline("\n");
console.writeline("\n");
console.writeline("-----------------------------------------------------------");
console.readline();
}
}
}
as you can see we are just updating the record as below once we get the response from await cons.getasync(“api/tbltags/2”) .
tag.tagname = "new tag";
res = await cons.putasjsonasync("api/tbltags/2", tag);
now, run your application again and check whether the tag name has been changed to 'new tag'.
web_api_consumer_put_output
now, did you see that your tag name has been changed? if yes, we are ready to go for our next operation. are you ready?
delete operation using httpclient
we will follow the same procedure for delete operation too. please see the code for delete operation below.
async task myapidelete(httpclient cons)
{
using (cons)
{
httpresponsemessage res = await cons.getasync("api/tbltags/2");
res.ensuresuccessstatuscode();
if (res.issuccessstatuscode)
{
res = await cons.deleteasync("api/tbltags/2");
console.writeline("\n");
console.writeline("\n");
console.writeline("-----------------------------------------------------------");
console.writeline("------------------calling delete operation--------------------");
console.writeline("------------------deleted-------------------");
console.readline();
}
}
}
to delete a record we uses res = await cons.deleteasync(“api/tbltags/2”); method. now, run your application and see the result.
web_api_consumer_delete_output
what action is pending now? yes, it is post.
post operation using httpclient
please add the below function to your project for the post operation.
static async task myapipost(httpclient cons)
{
using (cons)
{
var tag = new tbltag { tagname = "jquery", tagdescription = "this tag is all about jquery" };
httpresponsemessage res = await cons.postasjsonasync("api/tbltags", tag);
res.ensuresuccessstatuscode();
if (res.issuccessstatuscode)
{
console.writeline("\n");
console.writeline("\n");
console.writeline("-----------------------------------------------------------");
console.writeline("------------------calling post operation--------------------");
console.writeline("------------------created successfully--------------------");
}
}
}
we are just creating a new tbltag and assigning some values. once the object is ready, we will call the method postasjsonasync as follows.
var tag = new tbltag { tagname = "jquery", tagdescription = "this tag is all about jquery" };
httpresponsemessage res = await cons.postasjsonasync("api/tbltags", tag);
as you have noticed, i have not provided the tagid in the object... do you know why? i have already set identity specification with identity increment 1 in my table tbltags in sql database.
now, let's see the output. shall we?
web_api_consumer_post_output
we have done everything! that’s fantastic, right? happy coding!
you can also always use webclient for this requirement... i will share how in another article.
Published at DZone with permission of Sibeesh Venu, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments