How To Create And Consume Rest Service In C#
I must say, I never knew how easy and clear this topic of REST API is untill I did it myself. If you have whatever issues, mention it in the comment box by the left of this folio that says: 'Your Stance Matters' and you will recieve needed aid.
In this lesson nosotros are going to cover the following
- What is RESTful Web Services
- What is Residual API
- Task
- Solution: Creating RESTful API in Visual Studio(Footstep by Footstep)
- Step 1: Create an Empty Web API project
- Step two: Exam the Application
- Footstep three: Add a Controller
- Step iv: Add a Model(Employee form)
- Pace v: Create a list of Employees
- Footstep 6: Write the two Methods
- Step vii: Change the WebApiConfig.cs file
- Pace 8: Test the API
- Next Steps
Sentry the Video Lessons Here
What is RESTful Web Services?
First nosotros answer the question, what is a web service? A web service is is a piece of software or service that is accessible over the net. A web services can besides be used by other services or applications. For instance the weather service, or the currency commutation rates. If nosotros get to Google and blazon '100USD to EUR', a spider web service is called which executes the function to carry out the conversion. Here, 4 things happen:
- take the input parameters which are (the currency to convert from, the currency to convert to, and the value to convert)
- query a database to obtain the exchange rate between the two currencies
- do the calculation
- return the consequence(response) to the client
All of this is handled by a web service
These whole procedure is just the same every bit what happens during a function call. But in this case nosotros give information technology a fancy name 'spider web service' because it happens seamlessly over the web.
At present there are two types of web services:
Soap Web Services: Soap stands for Simple Object Admission Protocol and this is the traditional web service that take been around for some time. Lather is based on XML. Read more about Lather hither.
REST Web Services: REST stands for Representational State Transfer and is a newer type of spider web service. REST said to exist (not a protocol or standard) just an architechtural style. It support both XML and JSON. Read more than about REST hither.
What is Residuum API?
Again nosotros need to answer the question, 'what is an API?'. API stands for Application Developer's Interface and defined as 'a set of sub-routine definitions, tools and protocols for building a computer software'. An API is built using normal software development tools. Merely they are non complete applications. They are tools to exist used by other applications or past a programmer in developing an awarding.
An API based on REST is called REST API or RESTful API.
Lets not become into the practical aspect as this would assistance make information technology clearer for you. We would build a Residual API to solve the task below.
Job
Creaate a REST Web Service in .NET that exposes methods to
-
- Return a listing of employees
- Return an employee based on employeeID paramenter
Soltion: Creating RESTful API in Visual Studio(Step by Step)
We would cover thes seven unproblematic steps and at the end nosotros would have a complete spider web service in .Net that nosotros can access through a browser or any other Residual client.
You lot can use Visual Studio 2013, 2015 or 2017.
Step ane: Create an Empty Web API project
When you are creatinga new project, make sure y'all select Spider web API project as shown in the Figure ane.
Figure 1: Web API Template
Give the applicaiton a name and Click OK
Figure 2: Choose Empty, Select Spider web API
Make sure that the Web API checkbox is selected then you can click OK to create the application.
At this point the folders structure of your awarding is shown in Figure 3
Figure 3: Binder Structure
Step ii: Test the Application
Build and run the application in Chrome or Firefox or whatsoever other browser and ensure that the the home page is displayed as shown below. (Y'all can press F5 to run the application)
It opens the browser window and displays the error page shown in Figure 4. This is not a problem.
The error pages is displayed because we have non yet added whatsoever model, view or controller to our Residual API.
Close the browser window and finish application from running.
Step 3: Add together a Controller
Right-click on the Controller binder in the solution explorer and click on Add, an choose Controller
Choose – Web API 2 Controller – Empty
Figure 4: Adding Controller
Give information technology a name EmployeeController
Step 4: Add a Model (Employee model)
A controller is another grade in the Controllers folder of the solution that inherits from ApiController course.
- Right-click on the Model folder in the Solution Explorer and choose Add
- Click on New and choose Class.
- Enter the following code to the class to define our employee model.
public class Employee { public int EmployeeId { go; set; } public string Proper noun { get; ready; } public cord City { get; set; } }
List one: Employee Model Class
Step 5: Create a List of Employees
Create a hard-coded list of employees in the controller class. This is shown in Listing 2.
List<Employee> employees = new List<Employee>() { new Employee{EmployeeId=1, Name="Kindson", Metropolis ="Akokwa"}, new Employee{EmployeeId =2, Proper name="Oleander", City="Lagos"}, new Employee{EmployeeId =three, Proper noun="Saffron", City="Gbagada"} };
Listing ii: The Employees List
Pace 6: Write the two Methods
The first method would be a method that returns a list of employees.
The 2d method would take a parameter of an employeeId and return a particular employee that matches that particular id.
The two methods is shown in Listing 3
[HttpGet] public IEnumerable<Employee> getEmployees() { return employees; }
[HttpGet]
public IEnumerable<Employee> getEmployeeById( int id)
{
var Emp = from emp in getEmployees()
where emp.EmployeeId.Equals(id)
select emp;
render Emp.ToList<Employee>();
}
Listing 3: Methods to render list of employee and single employee
At this point the complete controller file would be like shown in Figure 5.
Figure 5: Final Controller File
Footstep 7: Modify the WebApiConfig.cs file
This file controls what the url that volition be typed into the browser to access the information.
Replace routeTemplate code with this ane:
api/{controller}/{activeness}/{id}
The complete WebAPIConfig.cs file will be every bit shown below.
Figure 6: WebAPIConfig File
At this betoken, we are gear up to test our API
Stride 8: Examination the API
- Rebuild and run the application.
- Run the applicaiton past pressing F5.
- The browser opens and displays an error page.
Now, in the browser address bar, suspend the following /api/Employee/getEmployees
The output would be as shown in Figure seven.
Figure vii: Final Output
As well examination for getEmployeeById
Now replace the url with this i /api/Employee/getEmployeeByID/1
If it displays a unmarried record, then you have successfully completed this tutorial
Next Steps
I would like to let you lot know that working with Web API does non become more hard than this. The next steps would also be every bit easy to follow as this one.
We would now learn well-nigh RestClient, which is a tool you use to test web services.
Thanks for reading!
For video lessons, subscribe to my YouTube channel on: Tech and Programming Lessons on YouTube
How To Create And Consume Rest Service In C#,
Source: https://kindsonthegenius.com/blog/restful-web-services-tutorial-1-creating-a-rest-api-in-visual-studio-net-c/
Posted by: smithwhane1992.blogspot.com
0 Response to "How To Create And Consume Rest Service In C#"
Post a Comment