What is REST
REST is the acronym that stands for: Representational State Transfer. REST is an architectural style of distributed system. It is based upon the set of principles that describes how network resources are defined and addressed. These set of principles was first described by “Roy Fielding” in 2000. REST is bigger than Web Services.
RESTful services uses HTTP (Hyper Text Transfer Protocol) to communicate. REST system interface with external systems as web resources identified by URIs (Uniform Resource Identifiers).
Constraints of REST
A Restful system should follow the constrains so it can be called Restful. There are 5 and 1 optional constraints of REST.
Http Verbs
Http verbs plays a very important role in the Restful Web API. The most common Http verbs are GET, PUT, POST and DELETE and these correspond to CRUD (Create, Read, Update and Delete) operations respectively.
The following Http Verbs exists:
REST is the acronym that stands for: Representational State Transfer. REST is an architectural style of distributed system. It is based upon the set of principles that describes how network resources are defined and addressed. These set of principles was first described by “Roy Fielding” in 2000. REST is bigger than Web Services.
RESTful services uses HTTP (Hyper Text Transfer Protocol) to communicate. REST system interface with external systems as web resources identified by URIs (Uniform Resource Identifiers).
Constraints of REST
A Restful system should follow the constrains so it can be called Restful. There are 5 and 1 optional constraints of REST.
Http Verbs
Http verbs plays a very important role in the Restful Web API. The most common Http verbs are GET, PUT, POST and DELETE and these correspond to CRUD (Create, Read, Update and Delete) operations respectively.
The following Http Verbs exists:
- Get
- Post
- Put
- Delete
- Trace
- Options
- Connect
- Patch
I will discuss here the most common used verbs and we will also see that how we can use these verbs in my next articles in which we will perform database operations with the help of the above Http verbs.
So, the following are the description of most common used Http verbs:
GET
As the name specifies, this verb is used to retrieve the data or information. It does not have any other effect except getting data.
Syntax
[HttpGet]
We can use the above syntax to define the method as a GET method. If we are retrieving the data from the database or displaying the data, then we can use this attribute to get the data.
Use
Let’s see an example of a GET method:
So, the following are the description of most common used Http verbs:
GET
As the name specifies, this verb is used to retrieve the data or information. It does not have any other effect except getting data.
Syntax
[HttpGet]
We can use the above syntax to define the method as a GET method. If we are retrieving the data from the database or displaying the data, then we can use this attribute to get the data.
Use
Let’s see an example of a GET method:
- [HttpGet, ActionName("GetInfo")]
- public HttpResponseMessage GetInfo()
- {
- //functional requirements
- }
Call
http://localhost:56828/api/sample/GetInfo
By the help of above Requested URI, we can get the information. Sample is the controller name.
POST
This verb is used to generate or create the resource. For example, If we have to add some information to the database then we must define the method as a POST method. The most common form to submit the data into the POST method is to pass the data into any entity object.
Syntax
[HttpPost]
We can use the above syntax to define the method as a POST method.
Use
- [HttpPost, ActionName("PostInfo")]
- public HttpResponseMessage PostInfo(Result result)
- {
- //functional requirements
- }
PUT
This verb is used to update the existing resource. For example, If we have to update some information to the database then we can define the method as a PUT method. We can send the data in the form of object as well as in a parameter too.
Syntax
[HttpPut]
We can use the above syntax to define the method as a PUT method.
Use
- [HttpPut, ActionName("UpdateInfo")]
- public HttpResponseMessage UpdateInfo(Result result)
- {
- //functional requirements
- }
DELETE
This verb is used to delete the existing resource. For example, If we have to delete some information to the database then we can define the method as a DELETE method. We can send the data in the form of object as well as in a parameter too.
Syntax
[HttpDelete]
We can use the above syntax to define the method as a DELETE method.
Use
- [HttpDelete, ActionName("DeleteInfo")]
- public HttpResponseMessage DeleteInfo(int UserId)
- {
- //functional requirements
- }
Demo
In the above section you have learned all the basics of RESTtful architecture and Web API. Now, in this section we will create the demo application in which we will perform the database operations from the ASP.NET Web API Application.
Prerequisites
If you want to create the demo then you must have Visual Studio 2012 or later version to do this. I am using here Visual Studio 2015.
Getting Started
Let’s create an ASP.NET Web API app in which we will perform the CRUD operations and later we will publish it into the Azure API. Now, just follow the procedure below to create the application.
Creating Web API Application
In this section, we will create the ASP.NET Web API application by following the steps below:
Step 1: Open the Visual Studio as an Administrator and click on “New Project”.
Figure 1: Visual Studio Start Page
Step 2: Select the Web tab from the left pane and then select ASP.NET Web Applicationto create the project.
Figure 2: Creating New Application
Step 3: In the next ASP.NET wizard select the Web API Project Template.
Figure 3: Web API Project Template
Now, Web API application is created successfully.
Perform Database Operations
In this section, we’ll perform database operation in which we will create the stored procedures to perform CRUD operations. I have created the database and tables with the record and stored procedures too. You can create the whole database from the following script or you can create your own database records. So, just follow the steps below:
Step 1: Just create the database from the following script:
CREATE DATABASE [Cricketer]
Step 2: Now from the following script the whole database is created with the tables and records and stored procs:
- USE[Cricketer]
- GO
- /****** Object: StoredProcedure [dbo].[CC_GetCricketerList] Script Date: 1/31/2016 8:50:44 PM ******/
- IFEXISTS(SELECT * FROMsys.objectsWHEREobject_id = OBJECT_ID(N '[dbo].[CC_GetCricketerList]') ANDtypein(N 'P', N 'PC'))
- DROP PROCEDURE[dbo].[CC_GetCricketerList]
- GO
- /****** Object: StoredProcedure [dbo].[CC_GetCricketerDetailsById] Script Date: 1/31/2016 8:50:44 PM ******/
- IFEXISTS(SELECT * FROMsys.objectsWHEREobject_id = OBJECT_ID(N '[dbo].[CC_GetCricketerDetailsById]') ANDtypein(N 'P', N 'PC'))
- DROP PROCEDURE[dbo].[CC_GetCricketerDetailsById]
- GO
- /****** Object: StoredProcedure [dbo].[CC_DeleteCricketerProfile] Script Date: 1/31/2016 8:50:44 PM ******/
- IFEXISTS(SELECT * FROMsys.objectsWHEREobject_id = OBJECT_ID(N '[dbo].[CC_DeleteCricketerProfile]') ANDtypein(N 'P', N 'PC'))
- DROP PROCEDURE[dbo].[CC_DeleteCricketerProfile]
- GO
- /****** Object: StoredProcedure [dbo].[CC_AddUpdateCricketerDetails] Script Date: 1/31/2016 8:50:44 PM ******/
- IFEXISTS(SELECT * FROMsys.objectsWHEREobject_id = OBJECT_ID(N '[dbo].[CC_AddUpdateCricketerDetails]') ANDtypein(N 'P', N 'PC'))
- DROP PROCEDURE[dbo].[CC_AddUpdateCricketerDetails]
- GO
- /****** Object: Table [dbo].[CricketerProfile] Script Date: 1/31/2016 8:50:44 PM ******/
- IFEXISTS(SELECT * FROMsys.objectsWHEREobject_id = OBJECT_ID(N '[dbo].[CricketerProfile]') ANDtypein(N 'U'))
- DROP TABLE[dbo].[CricketerProfile]
- GO
- /****** Object: Table [dbo].[CricketerProfile] Script Date: 1/31/2016 8:50:44 PM ******/
- SET ANSI_NULLSON
- GO
- SET QUOTED_IDENTIFIERON
- GO
- SETANSI_PADDINGON
- GO
- IFNOTEXISTS(SELECT * FROMsys.objectsWHEREobject_id = OBJECT_ID(N '[dbo].[CricketerProfile]') ANDtypein(N 'U'))
- BEGIN
- CREATE TABLE[dbo].[CricketerProfile](
- [ID][int] IDENTITY(1, 1) NOTNULL, [Name][varchar](50) NULL, [ODI][int] NULL, [Tests][int] NULL, [ODIRuns][int] NULL, [TestRuns][int] NULL,
- CONSTRAINT[PK_CricketerProfile] PRIMARYKEYCLUSTERED(
- [ID] ASC
- ) WITH(PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON[PRIMARY]
- ) ON[PRIMARY]
- END
- GO
- SETANSI_PADDINGOFF
- GO
- SETIDENTITY_INSERT[dbo].[CricketerProfile] ON
- GO
- INSERT[dbo].[CricketerProfile]([ID], [Name], [ODI], [Tests], [ODIRuns], [TestRuns]) VALUES(1, N 'Sachin Tendulkar', 463, 200, 18426, 15921)
- GO
- INSERT[dbo].[CricketerProfile]([ID], [Name], [ODI], [Tests], [ODIRuns], [TestRuns]) VALUES(2, N 'Saurav Ganguly', 311, 113, 11363, 7212)
- GO
- INSERT[dbo].[CricketerProfile]([ID], [Name], [ODI], [Tests], [ODIRuns], [TestRuns]) VALUES(3, N 'Rahul Dravid', 344, 164, 10889, 13228)
- GO
- INSERT[dbo].[CricketerProfile]([ID], [Name], [ODI], [Tests], [ODIRuns], [TestRuns]) VALUES(4, N 'V.V.S. Laxman', 86, 134, 2338, 8781)
- GO
- INSERT[dbo].[CricketerProfile]([ID], [Name], [ODI], [Tests], [ODIRuns], [TestRuns]) VALUES(5, N 'Virendar Sehwag', 251, 104, 8273, 8586)
- GO
- SETIDENTITY_INSERT[dbo].[CricketerProfile] OFF
- GO
- /****** Object: StoredProcedure [dbo].[CC_AddUpdateCricketerDetails] Script Date: 1/31/2016 8:50:45 PM ******/
- SETANSI_NULLSON
- GO
- SETQUOTED_IDENTIFIERON
- GO
- IFNOTEXISTS(SELECT * FROMsys.objectsWHEREobject_id = OBJECT_ID(N '[dbo].[CC_AddUpdateCricketerDetails]') ANDtypein(N 'P', N 'PC'))
- BEGIN
- EXEC dbo.sp_executesql @statement = N 'CREATE PROCEDURE [dbo].[CC_AddUpdateCricketerDetails] AS'
- END
- GO
- -- === === === === === === === === === === === === === === ===
- --Author: Nimit Joshi
- --Create date: 31 / 01 / 2016
- --Description: This sp is used to insert and update data in Cricketer Profile
- -- === === === === === === === === === === === === === === ===
- ALTERPROCEDURE CC_AddUpdateCricketerDetails
- --Add the parameters
- for the stored procedure here
- @Id INT = NULL,
- @Name VARCHAR(50),
- @ODI INT = NULL,
- @Tests INT = NULL,
- @OdiRuns INT = NULL,
- @TestRuns INT = NULL,
- @Type INT, --1
- for Add Record and 2
- for Update Record
- @Status INTOUT
- AS
- BEGIN
- --SET NOCOUNT ON added to prevent extra result sets from
- --interfering with SELECT statements.
- IF(@Type = 1)
- BEGIN
- IFNOTEXISTS(SELECT cp.Name FROM dbo.CricketerProfile(NOLOCK) cp WHERE cp.Name LIKE '%' + @Name + '%')
- BEGIN
- INSERT INTO dbo.CricketerProfile
- (
- Name,
- ODI,
- Tests,
- ODIRuns,
- TestRuns
- )
- VALUES(@Name, --Name - varchar(50) @ODI, --ODI - int @Tests, --Tests - int @OdiRuns, --ODIRuns - int @TestRuns--TestRuns - int);
- IF(@ @ROWCOUNT > 0)
- BEGIN
- SET @Status = 1;
- --Record inseted successfully!!
- END;
- END;
- ELSE
- BEGIN
- SET @Status = 2;
- --Record alredy exists!!
- END;
- END;
- ELSE
- IF(@Type = 2)
- BEGIN
- IFEXISTS(SELECT ccp.ID FROM dbo.CricketerProfile ccp(NOLOCK) WHERE ccp.ID = @Id)
- BEGIN
- UPDATE dbo.CricketerProfile
- SET Name = ISNULL(@Name, Name),
- ODI = ISNULL(@ODI, ODI),
- Tests = ISNULL(@Tests, Tests),
- ODIRuns = ISNULL(@OdiRuns, ODIRuns),
- TestRuns = ISNULL(@TestRuns, TestRuns)
- WHERE ID = @Id;
- IF(@ @ROWCOUNT > 0)
- BEGIN
- SET @Status = 3;
- --Record Updated Successfully!!
- END;
- END;
- ELSE
- BEGIN
- SET @Status = 4;
- --Record does not exists!!
- END;
- END;
- END;
- GO
- /****** Object: StoredProcedure [dbo].[CC_DeleteCricketerProfile] Script Date: 1/31/2016 8:50:45 PM ******/
- SETANSI_NULLSON
- GO
- SETQUOTED_IDENTIFIERON
- GO
- IFNOTEXISTS(SELECT * FROMsys.objectsWHEREobject_id = OBJECT_ID(N '[dbo].[CC_DeleteCricketerProfile]') ANDtypein(N 'P', N 'PC'))
- BEGIN
- EXEC dbo.sp_executesql @statement = N 'CREATE PROCEDURE [dbo].[CC_DeleteCricketerProfile] AS'
- END
- GO
- -- === === === === === === === === === === === === === === ===
- --Author: Nimit Joshi
- --Create date: 31 / 01 / 2016
- --Description: This sp is used to delete the records from the cricketer table.
- -- === === === === === === === === === === === === === === ===
- ALTERPROCEDURE[dbo].[CC_DeleteCricketerProfile]
- --Add the parameters
- for the stored procedure here
- @Id INT, @Status INTOUT
- AS
- BEGIN
- --SET NOCOUNT ON added to prevent extra result sets from
- --interfering with SELECT statements.
- IFEXISTS(SELECT cp.ID FROM dbo.CricketerProfile cp(NOLOCK) WHERE cp.ID = @Id)
- BEGIN
- DELETE FROM dbo.CricketerProfile
- WHERE ID = @Id;
- IF(@ @ROWCOUNT > 0)
- BEGIN
- SET @Status = 1;
- --Deleted Successfully!!
- END;
- END;
- ELSE
- BEGIN
- SET @Status = 2;
- --Record doesn 't exists
- END;
- END;
- GO
- /****** Object: StoredProcedure [dbo].[CC_GetCricketerDetailsById] Script Date: 1/31/2016 8:50:45 PM ******/
- SET ANSI_NULLSON
- GO
- SET QUOTED_IDENTIFIERON
- GO
- IFNOTEXISTS(SELECT * FROMsys.objectsWHEREobject_id = OBJECT_ID(N '[dbo].[CC_GetCricketerDetailsById]') ANDtypein(N 'P', N 'PC'))
- BEGIN
- EXEC dbo.sp_executesql @statement = N 'CREATE PROCEDURE [dbo].[CC_GetCricketerDetailsById] AS'
- END
- GO
- ALTER Proc[dbo].[CC_GetCricketerDetailsById]
- @ID int
- AS
- Begin
- select * from CricketerProfile(NOLOCK) where ID = @Id
- End
- GO
- /****** Object: StoredProcedure [dbo].[CC_GetCricketerList] Script Date: 1/31/2016 8:50:45 PM ******/
- SET ANSI_NULLSON
- GO
- SET QUOTED_IDENTIFIERON
- GO
- IFNOTEXISTS(SELECT * FROMsys.objectsWHEREobject_id = OBJECT_ID(N '[dbo].[CC_GetCricketerList]') ANDtypein(N 'P', N 'PC'))
- BEGIN
- EXEC dbo.sp_executesql @statement = N 'CREATE PROCEDURE [dbo].[CC_GetCricketerList] AS'
- END
- GO
- ALTERVProc[dbo].[CC_GetCricketerList]
- AS
- Begin
- select ID, Name from CricketerProfile(NOLOCK)
- End
- GO
In this section we will add new projects to associate the database with the Web API application. So, start with the following steps:
Step 1: Just add a new Solution Folder in your application named “Models”
Figure 4: Adding New Solution Folder
Step 2: Add a “New Project” in the Models folder
Figure 5: Adding New Project
Step 3: Select Class Library template to add a new project and name it “BestCricketers.Models”.
Figure 6: Adding Class Library
Step 4: Add a new class named “CricketerProfile” and replace the code with the following code:
- public class CricketerProfile: Result
- {
- public int Id
- {
- get;
- set;
- }
- public string Name
- {
- get;
- set;
- }
- public int ODI
- {
- get;
- set;
- }
- public int Tests
- {
- get;
- set;
- }
- public int OdiRuns
- {
- get;
- set;
- }
- public int TestRuns
- {
- get;
- set;
- }
- public int Type
- {
- get;
- set;
- }
- }
- public class Result
- {
- public int Status
- {
- get;
- set;
- }
- public string Message
- {
- get;
- set;
- }
- }
Step 6: Now add “Enterprise Library” Nuget Package,
Figure 7: Adding Enterprise Library Package
Step 7: Add a new class “CricketerDAL” in the DAL folder and replace the code with the following code:
- namespace BestCricketers.Core.DAL {
- publicclassCricketerDAL {
- #region Variable
- ///<summary>
- /// Specify the Database variable
- ///</summary>
- Database objDB;
- ///<summary>
- /// Specify the static variable
- ///</summary>
- staticstring ConnectionString;#
- endregion# region Constructor
- ///<summary>
- /// This constructor is used to get the connectionstring from the config file
- ///</summary>
- public CricketerDAL() {
- ConnectionString = ConfigurationManager.ConnectionStrings["CricketerConnectionString"].ToString();
- }
- #endregion
- #region Database Method
- publicList < T > ConvertTo < T > (DataTable datatable) whereT: new() {
- List < T > Temp = newList < T > ();
- try {
- List < string > columnsNames = newList < string > ();
- foreach(DataColumn DataColumn in datatable.Columns)
- columnsNames.Add(DataColumn.ColumnName);
- Temp = datatable.AsEnumerable().ToList().ConvertAll < T > (row => getObject < T > (row, columnsNames));
- return Temp;
- }
- catch {
- return Temp;
- }
- }
- publicT getObject < T > (DataRow row, List < string > columnsName) whereT: new() {
- T obj = newT();
- try {
- string columnname = "";
- string value = "";
- PropertyInfo[] Properties;
- Properties = typeof (T).GetProperties();
- foreach(PropertyInfo objProperty in Properties) {
- columnname = columnsName.Find(name => name.ToLower() == objProperty.Name.ToLower());
- if (!string.IsNullOrEmpty(columnname)) {
- value = row[columnname].ToString();
- if (!string.IsNullOrEmpty(value)) {
- if (Nullable.GetUnderlyingType(objProperty.PropertyType) != null) {
- value = row[columnname].ToString().Replace("$", "").Replace(",", "");
- objProperty.SetValue(obj, Convert.ChangeType(value, Type.GetType(Nullable.GetUnderlyingType(objProperty.PropertyType).ToString())), null);
- } else {
- value = row[columnname].ToString();
- objProperty.SetValue(obj, Convert.ChangeType(value, Type.GetType(objProperty.PropertyType.ToString())), null);
- }
- }
- }
- }
- return obj;
- }
- catch (Exception ex) {
- return obj;
- }
- }
- #endregion
- #region CricketerProfile
- ///<summary>
- /// This method is used to get the cricketer data
- ///</summary>
- ///<returns></returns>
- publicList < CricketerProfile > GetCricketerList() {
- List < CricketerProfile > objGetCricketers = null;
- objDB = newSqlDatabase(ConnectionString);
- using(DbCommand objcmd = objDB.GetStoredProcCommand("CC_GetCricketerList")) {
- try {
- using(DataTable dataTable = objDB.ExecuteDataSet(objcmd).Tables[0]) {
- objGetCricketers = ConvertTo < CricketerProfile > (dataTable);
- }
- }
- catch (Exception ex) {
- throw ex;
- returnnull;
- }
- }
- return objGetCricketers;
- }
- ///<summary>
- /// This method is used to get cricketers details by cricketer id
- ///</summary>
- ///<returns></returns>
- publicList < CricketerProfile > GetCricketerDetailsById(int Id) {
- List < CricketerProfile > objCricketerDetails = null;
- objDB = newSqlDatabase(ConnectionString);
- using(DbCommand objcmd = objDB.GetStoredProcCommand("CC_GetCricketerDetailsById")) {
- try {
- objDB.AddInParameter(objcmd, "@ID", DbType.Int32, Id);
- using(DataTable dataTable = objDB.ExecuteDataSet(objcmd).Tables[0]) {
- objCricketerDetails = ConvertTo < CricketerProfile > (dataTable);
- }
- }
- catch (Exception ex) {
- throw ex;
- returnnull;
- }
- }
- return objCricketerDetails;
- }
- ///<summary>
- /// This method is used to add update cricketer info
- ///</summary>
- ///<param name="cricketer"></param>
- ///<returns></returns>
- publicint AddUpdateCricketerInfo(CricketerProfile cricketer) {
- int result = 0;
- objDB = newSqlDatabase(ConnectionString);
- using(DbCommand objCMD = objDB.GetStoredProcCommand("CC_AddUpdateCricketerDetails")) {
- objDB.AddInParameter(objCMD, "@Id", DbType.Int32, cricketer.Id);
- if (string.IsNullOrEmpty(cricketer.Name)) objDB.AddInParameter(objCMD, "@Name", DbType.String, DBNull.Value);
- else objDB.AddInParameter(objCMD, "@Name", DbType.String, cricketer.Name);
- if (cricketer.ODI == 0) objDB.AddInParameter(objCMD, "@ODI", DbType.Int32, DBNull.Value);
- else objDB.AddInParameter(objCMD, "@ODI", DbType.Int32, cricketer.ODI);
- if (cricketer.Tests == 0) objDB.AddInParameter(objCMD, "@Tests", DbType.Int32, DBNull.Value);
- else objDB.AddInParameter(objCMD, "@Tests", DbType.Int32, cricketer.Tests);
- if (cricketer.OdiRuns == 0) objDB.AddInParameter(objCMD, "@OdiRuns", DbType.Int32, DBNull.Value);
- else objDB.AddInParameter(objCMD, "@OdiRuns", DbType.Int32, cricketer.OdiRuns);
- if (cricketer.TestRuns == 0) objDB.AddInParameter(objCMD, "@TestRuns", DbType.Int32, DBNull.Value);
- else objDB.AddInParameter(objCMD, "@TestRuns", DbType.Int32, cricketer.TestRuns);
- objDB.AddInParameter(objCMD, "@Type", DbType.Int32, cricketer.Type);
- objDB.AddOutParameter(objCMD, "@Status", DbType.Int16, 0);
- try {
- objDB.ExecuteNonQuery(objCMD);
- result = Convert.ToInt32(objDB.GetParameterValue(objCMD, "@Status"));
- }
- catch (Exception) {
- throw;
- }
- }
- return result;
- }
- ///<summary>
- /// This method is used to delete cricketer info
- ///</summary>
- ///<param name="cricketer"></param>
- ///<returns></returns>
- publicint DeleteCricketerInfo(CricketerProfile cricketer) {
- int result = 0;
- objDB = newSqlDatabase(ConnectionString);
- using(DbCommand objCMD = objDB.GetStoredProcCommand("CC_DeleteCricketerProfile")) {
- objDB.AddInParameter(objCMD, "@Id", DbType.Int32, cricketer.Id);
- objDB.AddOutParameter(objCMD, "@Status", DbType.Int16, 0);
- try {
- objDB.ExecuteNonQuery(objCMD);
- result = Convert.ToInt32(objDB.GetParameterValue(objCMD, "@Status"));
- }
- catch (Exception) {
- throw;
- }
- }
- return result;
- }
- #endregion
- }
- }
- namespace BestCricketers.Core.BL {
- publicclassCricketerBL {
- ///<summary>
- /// This method is used to get the cricketer list
- ///</summary>
- ///<returns></returns>
- publicList < CricketerProfile > GetCricketerList() {
- List < CricketerProfile > ObjCricketers = null;
- try {
- ObjCricketers = newCricketerDAL().GetCricketerList();
- }
- catch (Exception) {
- throw;
- }
- return ObjCricketers;
- }
- ///<summary>
- /// This method is used to get cricketers details by cricketer id
- ///</summary>
- ///<returns></returns>
- publicList < CricketerProfile > GetCricketerDetailsById(int Id) {
- List < CricketerProfile > ObjCricketerDetails = null;
- try {
- ObjCricketerDetails = newCricketerDAL().GetCricketerDetailsById(Id);
- }
- catch (Exception) {
- throw;
- }
- return ObjCricketerDetails;
- }
- ///<summary>
- /// This method is used to add update cricketer info
- ///</summary>
- ///<param name="cricketer"></param>
- ///<returns></returns>
- publicint AddUpdateCricketerInfo(CricketerProfile cricketer) {
- int result = 0;
- try {
- result = newCricketerDAL().AddUpdateCricketerInfo(cricketer);
- }
- catch (Exception) {
- return 0;
- }
- return result;
- }
- ///<summary>
- /// This method is used to delete cricketer info
- ///</summary>
- ///<param name="cricketer"></param>
- ///<returns></returns>
- publicint DeleteCricketerInfo(CricketerProfile cricketer) {
- int result = 0;
- try {
- result = newCricketerDAL().DeleteCricketerInfo(cricketer);
- } catch (Exception) {
- return 0;
- }
- return result;
- }
- }
- }
Creating Web API
In this section, we will work on the ASP.NET Web API application. We will add the new Empty Web API Controller in which we will create some methods to call the CricketerBL class for performing the CRUD operations.
So, let’s begin with the following procedure:
Step 1: At first, in the API project, right click on the Controllers folder and goto Add, then click Controller,
Figure 8: Adding New Controller
Step 2: Select the “Web API 2 Controller - Empty” in the next wizard
Figure 9: Add Scaffold Wizard
Step 3: Now enter the controller name as “CricketersController”
Figure 10: Adding Controller
Step 4: Add the following connection string in the “<ConnectionStrings>” tab in your “Web.config” file of the API project:
- <add name="CricketerConnectionString"connectionString="Data Source=Your Server Name;Initial Catalog=Cricketer;User Id=Your User Id;Password=Your Password"providerName="System.Data.SqlClient" />
Note:
Add the references of Core and Models project into the API project before adding methods in the API Controller.
GET
We will create two types of GET methods in here. In first method we will get the list of Cricketers and in the second method we will pass the CricketerId to get the cricketer details.
Now add the two GET methods with the following code:
- using BestCricketers.Core.BL;
- using BestCricketers.Models;
- using System;
- using System.Collections.Generic;
- using System.Net;
- using System.Net.Http;
- using System.Web.Http;
- namespace BestCricketers.Controllers {
- publicclassCricketersController: ApiController {
- #region Variable
- HttpResponseMessage response;
- CricketerBL cricketerBL;
- #endregion# region Public Method
- ///<summary>
- /// This method is used to get cricketer list
- ///</summary>
- ///<returns></returns>
- [HttpGet, ActionName("GetCricketerList")]
- publicHttpResponseMessage GetCricketerList() {
- Result result;
- cricketerBL = newCricketerBL();
- try {
- var cricketerList = cricketerBL.GetCricketerList();
- if (!object.Equals(cricketerList, null)) {
- response = Request.CreateResponse < List < CricketerProfile >> (HttpStatusCode.OK, cricketerList);
- }
- }
- catch (Exception ex) {
- result = newResult();
- result.Status = 0;
- result.Message = ex.Message;
- response = Request.CreateResponse(HttpStatusCode.InternalServerError, result);
- }
- return response;
- }
- ///<summary>
- /// This method is used to get cricketer list by id
- ///</summary>
- ///<returns></returns>
- [HttpGet, ActionName("GetCricketerInfoById")]
- publicHttpResponseMessage GetCricketerInfoById(int CricketerId) {
- Result result;
- cricketerBL = newCricketerBL();
- try {
- var cricketerList = cricketerBL.GetCricketerDetailsById(CricketerId);
- if (!object.Equals(cricketerList, null)) {
- response = Request.CreateResponse < List < CricketerProfile >> (HttpStatusCode.OK, cricketerList);
- }
- }
- catch (Exception ex) {
- result = newResult();
- result.Status = 0;
- result.Message = ex.Message;
- response = Request.CreateResponse(HttpStatusCode.InternalServerError, result);
- }
- return response;
- }#endregion
- }
- }
We have successfully created the Web API Controller. Now we will run this application and call our GET methods. We will use POSTMAN to call the GET methods which is easy to use. We can use the Fiddler too.
You can get the POSTMAN from here.
Step 1: Debug the application.
Step 2: Now open the POSTMAN and at first copy the url from the browser and use that url as I used in the following screenshot:
Call Url: http://localhost:64016/api/Cricketers/GetCricketerList,
Figure 11: Simple GET Call
Get Call with Parameter
Call Url: http://localhost:64016/api/Cricketers/GetCricketerInfoById?Cricketerid=1
Figure 12: Get Call with Parameter
Now add the following three methods in the controller with which we can checkout the POST, PUT and DELETE methods :
POST
In this call, all the data will be send as an object. In POST call, data should be passed in the form of object and sometimes it depends on the condition and you can send the data in the form of FormData.
Here, I am sending the data in the form of object. So, let’s create the method for POST call with the following code:
- ///<summary>
- /// This method is used to add cricketer info in the database.
- ///</summary>
- ///<returns></returns>
- [HttpPost, ActionName("AddCricketerInfo")]
- publicHttpResponseMessage AddCricketerInfo(CricketerProfile Cricketer) {
- Result ObjResult;
- int result;
- cricketerBL = newCricketerBL();
- try {
- result = cricketerBL.AddUpdateCricketerInfo(Cricketer);
- if (result > 0) {
- if (result == 1) {
- ObjResult = newResult();
- ObjResult.Status = result;
- ObjResult.Message = "Record Inserted Successfully!!";
- response = Request.CreateResponse < Result > (HttpStatusCode.OK, ObjResult);
- }
- elseif(result == 2) {
- ObjResult = newResult();
- ObjResult.Status = result;
- ObjResult.Message = "Record Already Exists!!";
- response = Request.CreateResponse < Result > (HttpStatusCode.OK, ObjResult);
- }
- else {
- ObjResult = newResult();
- ObjResult.Status = result;
- ObjResult.Message = "Record Not Added!!";
- response = Request.CreateResponse < Result > (HttpStatusCode.OK, ObjResult);
- }
- }
- }
- catch (Exception ex) {
- ObjResult = newResult();
- ObjResult.Status = 0;
- ObjResult.Message = ex.Message;
- response = Request.CreateResponse(HttpStatusCode.InternalServerError, ObjResult);
- }
- return response;
- }
http://localhost:64016/api/Cricketers/AddCricketerInfo
At first add the Header as in the following screenshot:
Figure 13: Headers in POST Call
Now click on Send,
Figure 14: POST Call in Web API
In the above figure you can see your api is showing the response.
PUT
In this method we will add the method defined as HttpPut verb with which we can update the data. So, add the following code in the Controller:
- ///<summary>
- /// This method is used to update cricketer info in the database.
- ///</summary>
- ///<param name="Cricketer"></param>
- ///<returns></returns>
- [HttpPut, ActionName("UpdateCricketerInfo")]
- publicHttpResponseMessage UpdateCricketerInfo(CricketerProfile Cricketer)
- {
- Result ObjResult;
- int result;
- cricketerBL = newCricketerBL();
- try {
- result = cricketerBL.AddUpdateCricketerInfo(Cricketer);
- if (result > 0)
- {
- if (result == 3)
- {
- ObjResult = newResult();
- ObjResult.Status = result;
- ObjResult.Message = "Record Updated Successfully!!";
- response = Request.CreateResponse<Result>(HttpStatusCode.OK, ObjResult);
- }
- elseif (result == 2)
- {
- ObjResult = newResult();
- ObjResult.Status = result;
- ObjResult.Message = "Record does not Exists!!";
- response = Request.CreateResponse<Result>(HttpStatusCode.OK, ObjResult);
- }
- else
- {
- ObjResult = newResult();
- ObjResult.Status = result;
- ObjResult.Message = "Record Not Added!!";
- response = Request.CreateResponse<Result>(HttpStatusCode.OK, ObjResult);
- }
- }
- }
- catch (Exception ex)
- {
- ObjResult = newResult();
- ObjResult.Status = 0;
- ObjResult.Message = ex.Message;
- response = Request.CreateResponse(HttpStatusCode.InternalServerError, ObjResult);
- }
- return response;
- }
http://localhost:64016/api/Cricketers/UpdateCricketerInfo
Now change the HttpVerb to PUT and click on send after defining the updating values as per the following screenshot:
Figure 15: Put Call in Web API
In the above screenshot you can that see that record is successfully updated.
DELETE
In this method we will delete the CricketerInfo from the database. So we will create the method for deleting info and define it as HttpDelete. Add the following code in the Controller:
- ///<summary>
- /// This method is used to delete the cricketer info
- ///</summary>
- ///<param name="CricketerId"></param>
- ///<returns></returns>
- [HttpDelete, ActionName("DeleteCricketerInfo")]
- publicHttpResponseMessage DeleteCricketerInfo(int CricketerId)
- {
- Result ObjResult;
- int result;
- cricketerBL = newCricketerBL();
- try
- {
- CricketerProfile cricketer = newCricketerProfile();
- cricketer.Id = CricketerId;
- result = cricketerBL.DeleteCricketerInfo(cricketer);
- if (result > 0)
- {
- if (result == 1)
- {
- ObjResult = newResult();
- ObjResult.Status = result;
- ObjResult.Message = "Record Deleted Successfully!!";
- response = Request.CreateResponse<Result>(HttpStatusCode.OK, ObjResult);
- }
- elseif (result == 2)
- {
- ObjResult = newResult();
- ObjResult.Status = result;
- ObjResult.Message = "Record does not Exists!!";
- response = Request.CreateResponse<Result>(HttpStatusCode.OK, ObjResult);
- }
- else
- {
- ObjResult = newResult();
- ObjResult.Status = result;
- ObjResult.Message = "Record Not Found!!";
- response = Request.CreateResponse<Result>(HttpStatusCode.OK, ObjResult);
- }
- }
- }
- catch (Exception ex)
- {
- ObjResult = newResult();
- ObjResult.Status = 0;
- ObjResult.Message = ex.Message;
- response = Request.CreateResponse(HttpStatusCode.InternalServerError, ObjResult);
- }
- return response;
- }
http://localhost:64016/api/Cricketers/DeleteCricketerInfo?CricketerId=6
Now change the HttpVerb to DELETE and click on send as per the following screenshot:
Figure 16: DELETE Call in Web API
That’s it. We have successfully created a Web API Controller in which we have used the most commonly used methods (GET, PUT, POST and DELETE).
No comments:
Post a Comment