Web API
Web API stands for web application programming interface. It is a framework for building HTTP services that can be consumed by a broad range of clients including desktop clients, browsers, mobiles, iPhone and tablets. Programmatically, a Web API project is very similar to ASP.NET MVC since it uses the MVC design with features such as routing, controllers, actions filter models and binders etc. It is a part of the core ASP.NET platform and can be used with MVC and other type of web applications.
MVC
MVC stands for model view controller. It is a software architectural pattern for implementing user interfaces. In MVC, a project is separated into three interconnected parts, i.e., model, view, and controller.
- Model - Database operations such as fetch data, add data, update data etc.
- View - User can interact with the system like HTML and XAMARIN.
- Controller - Contains the business logic and provides communication between model and view.
How to create the new Web API project?
Steps
- Open Visual Studio and create a new project. Select Visual C# > Web > in the left side left side and select ASP.NET Web Applications (.NET Framework) template, provide a project name and click OK.
- Select Empty template and check MVC and Web API checkboxes and click OK.
- Your project is created. You're now in Solution Explorer. Right click on the Models folder and Add a new class and call it "Students".
- Our Students class will have fields. In my case, I add ID, UserName, Password, and ContactNo. You can add other fields whatever you like. Here is my class with public properties.
- {
- public int ID {
- get;
- set;
- }
- public string UserName {
- get;
- set;
- }
- public string Password {
- get;
- set;
- }
- public string ContactNo {
- get;
- set;
- }
- }
- Add the controller with select the 3rd no of controller to submit the data for new student. This dialogue box will appear you select your class name in a model class and write the db after the name of the project.
- Copy the students/create and paste in the browser. Now build and run the project.
- Now open the URL in a browser. Here you can create Students records. Enter students data and click Create button to save it.
- Add the 5th controller by Right Click on the Controllers in your project and add a Model class.
- Copy the api/students1 and paste in the search bar on browser. Build and run the project.
10. Open URL in the browser and you will see output like this.
How to update the data of students by using Web API?
Steps
- Create the new project of Xamarin.Form and write the following code to build the UI. As you can see from this XAML code, I've used a ListView and DataTemplate to bind Label controls to the fields.
- <ListView x:Name="LV">
- <ItemTemplate>
- <DataTemplate>
- <ViewCell>
- <StackLayout>
- <Label Text="{Binding ID}"/>
- <Label Text="{Binding UserName}"/>
- <Label Text="{Binding Password}"/>
- <Label Text="{Binding ContactNo}"/>
- </StackLayout>
- </ViewCell>
- </DataTemplate>
- </ItemTemplate>
- </ListView>
- Open the .cs file of the main page and write the code after initialize component. The GetStudents method connects to the WebAPI and gets the list of Students. After that, the resultset is bound to the ListView using LV.ItemsSource property. The student returned var is a collection of students.
- Getstudents();
- }
- public async void Getstudents()
- {
- var httpClient = new HttpClient();
- var response = await httpClient.GetStringAsync("http://localhost:61747/api/students1");
- var student = JsonConvert.DeserializeObject < List < students >> (response);
- LV.ItemsSource = student;
- }
- Now, add a new class with the name of Signup and write the following code. It adds these fields, ID, UserName, Password, and ContactNo.
HTTP Client
It stands for hypertext transfer protocol. HTTP Client makes a request which communicate to the server what action they want performed.
DeserializeObject
it converts the JSON strings into .NET Object and take the data from database.
SerializeObject
it converts the .NET objects into JSON string.
- Add another form, a new page with the name of UpdateStudent and add a StackLayout with the following fieds. On this page, we will add new student data.
- <StackLayout>
- <Entry Placeholder="ID" x:Name="Id"/>
- <Entry Placeholder="UserName" x:Name="username"/>
- <Entry Placeholder="Password" x:Name="Password"/>
- <Entry Placeholder="ContactNo" x:Name="Number"/>
- <Button Text="Updatestudent" x:Name="Updatestudent" Clicked="Updatestudent_Clicked"/>
- </StackLayout>
- Open the cs file of updatestudents and write the following code. This code creates a Signup object, sets its properties after reading from the form, and calls WebAPI's method to push data to the database.
- Signup student = new Signup
- {
- ID = Convert.ToInt16(Id.Text),
- UserName = username.Text,
- Password = Password.Text,
- ContactNo = Number.Text
- };
- var httpClient = new HttpClient();
- var json = JsonConvert.SerializeObject(student);
- HttpContent httpContent = new StringContent(json);
- httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
- httpClient.PutAsync(String.Format("http://localhost:61747/api/students1/{0}", student.ID), httpContent);
- DisplayAlert("Added", "Your data has been Updated", "ok");
- Now, build and run the application. You will see UI with fields. Enter data and click Updatestudent.
7. The new update date looks like the following:
Summary
In this step by step tutorial, I showed how to create a Web API project, connect it with a database, add data records using Web API for a Student Registration form.