One of my best tutorial in past is Restful API for Android using Asp.net and SQL Server. This tutorial is deprecated and now there are better ways to do this. So this would be the tutorial that will cover on that topic.

I’m using
Visual Studio 2015 Update 2 and SQL Server 2014

 

First start with a new Web API project in Visual Studio.

From New Project window create an ASP.NET Web Application project.

create new project

 

Select the WebAPI template from template window and click OK

Select Project template

Now Visual Studio will create all required files and folder for you and add all required nugget packages need by simple web application. So nothing to worry 😀 . If we need anything later we’ll add those later. Now we are good to go.

Next we need to create a new database for our application. I’ll use SQL server as my DB.

Start SQL Server and connect to your local database.

Right click Database folder in Object Explorer and select New Database as below

create db

Give a database name in and click OK to create a new Database in your local pc.

I named my database as T_WebApiApp

create db

Now database is created and we can move to Visual Studio to develop the Web API.

I’m using Entity Framework 6 ORM with code first approach to manipulate with database. It’s up to you use your own comfortable ORM or any other methods to connect to database.

I will implement below user stories.

  1. I’m a teacher I need to add new student to system : Create Student
  2. I’m a teacher I need to update student details : Update Student
  3. I’m a teacher I need to remove students from database : Delete Student
  4. I’m a teacher I need to view student details – View Student
  5. I’m a teacher I need to view all student in my class – View All Students

Since we are using EF code-first method we need a model to interact with. So Let’s create a Student class in our Model folder and add properties.

  • Right click on the Model folder in solution explorer
  • Go to Add sub menu
  • Click on New Item 

From Add new Item window search for class and add a new class name Student

Student Class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace TC_WebAPIProjectForAndroidIOS.Models
{
    public class Student
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public DateTime BirthDay { get; set; }
        public string Gender { get; set; }
        public string Address { get; set; }

    }
}

Since we have the student class lets implement the connection between SQL server and our application.

Add a connection string to Web.Config file

 <connectionStrings>
    <add name ="Connection" connectionString="Data Source=AHAMEDISHAK-D;Initial Catalog=T_WebApiApp;Integrated Security=True" providerName="System.Data.SqlClient"/>
 </connectionStrings>

Create a new folder call DBA in your solution

Add a new class named ApiDbContext. This class is responsible to create the connection between DB. Update the class as following,

using System.Data.Entity;
using TC_WebAPIProjectForAndroidIOS.Models;

namespace TC_WebAPIProjectForAndroidIOS.DBA
{
    public class ApiDbContext :DbContext
    {
        public ApiDbContext() : base("Connection")
        {
                
        }

         public DbSet<Student> Students { get; set; }
    }
}

Now we are done with our DB connection. Next we need to change the route for our API.

Open the WebApiConfig file in App_Start

Modify the DefaultApi route as following

  config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

 

Now we are done  with our configurations. Next we move to implement our user stories.

First of all we need to add a new Controller to our application. Add a controller named StudentAPIController.

  • Right click on Controllers folder
  • Go to Add sub menu
  • Click Controller…
  • From Add Scaffold window
  • Select Web API 2 Controller – Empty
  • Click Add
  • Give the Controller Name as StudentAPIController
  • Click Add.

 

 One you added the Controller, initialize a dbContext variable and instantiate it within the controller constructor as below

   ApiDbContext dbContext=null;
        public StudentAPIController()
        {
            dbContext = new ApiDbContext();
        }

Ones you done it we can use dbContext to manipulate with database. So now we implement user stories one by one.

  1. I’m a teacher I need to add new student to system : Create Student

Add new action method named InsertStudent and implement the method as below

  [HttpPost]
        public IHttpActionResult InsertStudent(Student student)
        {

            dbContext.Students.Add(student);
            dbContext.SaveChangesAsync();

            return Ok(student.Id);
        }

2. I’m a teacher I need to view all student in my class – View All Students

Add new action method named GetAllStudent and implement the method as below


        public IEnumerable<Student> GetAllStudent()
        {
             var list=dbContext.Students.ToList();

            return list;
        }

3. I’m a teacher I need to remove students from database : Delete Student

Add new action method named DeleteStudent and implement the method as below

        [HttpGet]
        public IHttpActionResult DeleteStudent(int id)
        {
           var student= dbContext.Students.Find(id);

            dbContext.Students.Remove(student);

            dbContext.SaveChangesAsync();

            return Ok(student.FirstName+" "+student.LastName+" is deleted successfully." );

        }

4. I’m a teacher I need to view student details – View Student

Add new action method named ViewStudent and implement the method as below

        [HttpGet]
        public IHttpActionResult ViewStudent(int id)
        {
            var student = dbContext.Students.Find(id);
            return Ok(student);
        }

5. I’m a teacher I need to update student details : Update Student

Add new action method named UpdateStudent and implement the method as below

        [HttpPost]
        public IHttpActionResult UpdateStudent(Student student)
        {

            var std = dbContext.Students.Find(student.Id);

            std.FirstName = student.FirstName;
            std.LastName = student.LastName;
            std.BirthDay = student.BirthDay;
            std.Gender = student.Gender;
            std.Address = student.Address;

            dbContext.Entry.Student.State = System.Data.Entity.EntityState.Modified;
            dbContext.SaveChangesAsync();

            return Ok();
        }

Now we are done with our user stories so we can run this to check our API is working or not. I‘ll use Google Chrome web app called Postman to call this API.

Before you use postman run the API and get the localhost url to access the API through postman.

Let’s try our API.

  1. Insert a new Student

Method Type : POST

 
{
    FirstName:"Rayan",
    LastName: "Linkon",
    Birthday:"04/04/1991",
    Gender: "Male",
    Address:"No 5,Michel Road, Colombo 6"
}

Insert Student JSON Request

2. View All Students in Database

Request

View all Student Request

Response

View All Student Response

3. View Student

Request

View Student Request

Response

View Student Response 4. Delete Student

Request

Delete Student Request

Response

Delete Student Response5. Update Student

Update Student Request

All the methods are working perfectly. You can use this API in your application.

Thank you for visiting this website. Subscribe to website to get more of this tutorial.

  • John

    Excellent article – thanks.

    What is the line in the UpdateStudent action method that starts with dbContext.Entry?

    Also, what do i have to do to get EF to create the database table?

    Thanks,

    John

  • Anh

    You can guide use web api 2 for android ^_^ ? Thank you

  • Raul

    Having an issue with this line of code.. Im sure you copied and pasted it correctly or something. Mind clarifying?

    // method UpdateStudent() in StudentController.cs
    dbContext.Entry&amp;amp;amp;lt;Student&amp;amp;amp;gt;(std).State = System.Data.Entity.EntityState.Modified;

  • william

    Could you please expand it with an example where you can upload an image
    from the android application ?, thank you very much for considering my
    request….