You are on page 1of 15

Restful API for Android using ASP.


Server Part 1
By Ahamed Ishak - Mar 12, 2014

Message from Author

Following tutorial is currently not up to date and

there are lots of bug in it. Please dontuse this
tutorial to any of yourproduction work.

Please clickbelow link to the new tutorial in restful api

Restful API for Android and IOS using ASP.NET Web API 2

Thank you

Most of the android applications use an API (Application Programming

Interface) for send and receive data from servers to client (App). API is very
useful when application need to show dynamic data to end user. For an
instance think how Gmail app receives emails? It uses an API to communicate
with Google mail server. When there is a new email, server noties the
application through API. Flipboard application also uses the same mechanism
to update ipboard. When ipboard server database is updated it noties the
app then application download the data through API. This is the basic usage of
APIs in android.

In this tutorial Ill show you how to create a restful API for android (JSON
based API)application using and Microsoft SQL Server Database. You
can use MySQL or other databases instead of SQL server. Ill use SQL server
because it is easy to use with (Both are Microsoft Products). Ill try to
make this tutorial simple and clear to understand. If you nd any issue please
feel free to ask. You can use the comment section to communicate with me.

Demo Video

This tutorial is quite long; to make it simple I divided it to two parts. In this
tutorial (Part 1) Ill cover the Creation of the API using and SQL Server.
InRestful API for Android Part 2Ill cover how to implement this API in
Android Application.


Overview Of the tutorial

This tutorial will show you the basic implementation of the restful API. Ill show
you how to connect android application with SQL server through a restful API.
In android application users able create a user account and login to the
account through the restful API. Application will retrieve department details
from SQL Server database and display in a listview.

Step 1: Download Resources

Download and extract the resource les need to implement the restful API from
below download button.

Download DLL Files

Json Services : [quote_box_center]
Ill use C# as the primary programming language in Visual Studio 2012. I will
use .NET Framework 4.5 to demonstrate this tutorial. This is also work with
.NET Framework 3.5 and .NET Framework 4.


Step 2: Creating a Project and Initialization

Open Visual Studio and create an ASP.NET Empty Web Application project.
Project name is JSONWebAPI. Follow below steps to create the project.

1. Go to File=>New Click Project or Press Ctrl+Shift+N

2. From the New Project window select Web category from left panel
3. Then Select ASP.NET Empty Web Application from center panel
4. Give Name as JSONWebAPI
5. Select project Location from Browse (Or keep the default)
6. Make sure Create directory for solution is checked
7. Click OK button

Create New Project

Now you need to add those dll les in JsonServices (0.3.4) folder in
downloaded resource to the.NET Web Application. Follow below steps to add
dll le to the project.
1. Right click on JSONWebAPI project in Solution Explorer
2. From the menu click on Add Reference item to open the Reference
3. Click Browse from the left panel
4. Then click Browse button at bottom of Reference Manager
5. Then go to the location where you extract the downloaded Resource Files
6. Then select all three .dll les and click Add button
7. Then click OK button (Make sure to checked all three le)

Add DLL Files as Reference

Now you need to add a Generic Handler to your Solution Explore. Follow
below steps.

1. Go to PROJECT menu in Visual Studio 2012 then click Add New Item
2. From Add New Item window select Web category from left panel
3. From center panel select Generic Handler
4. Keep the default Name Handler1.ashx
5. Then click Add button

Now create three classes namely ServiceAPI.cs, IServiceAPI.cs and

DBConnect.cs. Follow below steps to create a new class
1. Go to PROJECT menu then click Add New Item
2. From left panel select Code category
3. Select Class item from center panel
4. Give the class name as ServiceAPI.cs
5. Click Add button

Repeat the same instruction to create IServiceAPI.cs and DBConnect.cs


Step 3: SQL Server Database Creation and

Now we jump from visual studio to SQL server. Ill not go in-depth about SQL
Server. Ill only show you basic stu you need to know in order to complete this
tutorial. If you are beginner then follow all the instruction carefully.

Firstly open the SQL Server Management Studio and connect to the server.
Please keep the server name in your mind. Later you need that Server Name to
connect to SQL Server from API. In my case it is AHAMEDISHAK

Connect To SQL Server

Press Connect button to connect your Server. Now Ill do the tutorial part by

1. Create a New Database

To create a new database called AndroidAppDB follow the below steps

1. Select New Database from right clicking Database folder in Object

2. In New Database window give the Database Name as AndroidAppDB
3. Then click OK button to create the database.

2. Create Database Tables

Before create tables create a New Query le and select the correct database.
In this case AndroidAppDB. If youre a beginner keep this in mind because
before doing any updates to a database we need to select database rst. It is
very important step you need to follow every time you update the database
through a Query le.

Select Correct Database

Now Execute below sql queries to create table. Ill create two tables.

SQL Queries to Create Tables and Insert Data

2 -------------Table 1: UserDetails (To store user information
4 CREATE TABLE UserDetails (
6 firstName VARCHAR(50),
lastName VARCHAR(50),
7 userName VARCHAR(50),
8 p
password VARCHAR(50),
9 );
11 -------------Table 2: Dept (To store Department information)
15 n
no INT,
16 n
name VARCHAR(50),
18 P
19 );
21 ----------------------Insert data to Dept Table-------------
23 INSERT INTO Dept VALUES (1,'Accounting');
24 INSERT INTO Dept VALUES (2,'Marketing');
25 INSERT INTO Dept VALUES (3,'Information Technology');
26 INSERT INTO Dept VALUES (4,'Networking');
27 INSERT INTO Dept VALUES (5,'Management');
28 INSERT INTO Dept VALUES (6,'Medical');
29 INSERT INTO Dept VALUES (7,'Electronics');
30 INSERT INTO Dept VALUES (8,'Finance');
31 INSERT INTO Dept VALUES (9,'Engineering');
32 INSERT INTO Dept VALUES (10,'Defense');

Step 4: Connect and Congure the SQL

Server Database to JSONWebAPI
Now come back to Visual Studio. Next part of the tutorials is to connect the
newly created database to our API project. By doing this we can
programmatically retrieve and update information in database. To congure the
connection open the Web.cong le in Solution Explorer. Update your le by
adding below conguration lines. Please add below lines between
<conguration> and </conguration>

Web.config updates
2 ConString" connectionString="Data Source=AHAMEDISHAK; Initial

Above conguration code is used to connect SQL Server database in my PC.

So this will not work for your API until you change the Data Source value to
your Server Name. Simply delete the AHAMEDISHAK value and use your
SQL Server Name there. Catalog value should be the database name. If
you need to connect dierent database give the correct Database Name there.
ConString is the name of the Connection String. If you need to connect
more than one database at same time you need to create a new Connection
String with dierent name and congurations.

Next Open the DBConnect.cs class. This class is used to connect with the
database. Update your class according to below code. Dont forget to add
correct header les. Otherwise it will show you errors.

2 using System.Configuration;
3 using System.Data.SqlClient;
5 namespace JSONWebAPI
6 {
7 ///
8 /// This class is used to connect to sql server database
9 ///
10 public class DBConnect
11 {
13 p
private static SqlConnection NewCon;
14 p
private static string conStr = ConfigurationManager.
16 p
public static SqlConnection getConnection()
17 {
18 NewCon = new SqlConnection(conStr);
19 r
return NewCon;
21 }
22 p
public DBConnect()
23 {
25 }
27 }

Now connecting and conguration part is over.

Step 5: Lets Code

Next we need to congure the API interface which is used to handle the
communication between android application and API. To congure the API
interface open the Handler1.ashx le. Delete the example codes given in the
le. Update the Handler1.ashx according to below code. Use correct header
les in your code.
2 using JsonServices;
3 using JsonServices.Web;
5 namespace JSONWebAPI
6 {
7 p
public class Handler1 : JsonHandler
8 {
9 p
public Handler1()
10 {
11 t
this.service.Name = "JSONWebAPI";
12 t
this.service.Description = "JSON API for android
13 InterfaceConfiguration IConfig = new InterfaceCo
14 t
15 }
17 }

Now you need to do some small changes to IServiceAPI.cs and

ServiceAPI.cs class. IServiceAPI.cs should be an interface instead of a
class. To change the IServiceAPI.cs to an interface open the le and change
the class keyword to interface. Next ServiceAPI.cs class should extend the
IServiceAPI.cs interface. See below codes to if you didnt understand.

2 namespace JSONWebAPI
3 {
4 p
public interface IServiceAPI
5 {
7 }

2 namespace JSONWebAPI
3 {
4 p
public class ServiceAPI : IServiceAPI
5 {
7 }

Interface is similar to class le. Main dierent is we only declare methods in
interface. We will not implement any method in interface. Interface is extends
by a class. Class which extends the interface should implement all the methods
in interface.

Now open the IServiceAPI.cs interface le. Add following method
declarations according to below code.

2 using System.Data;
4 namespace JSONWebAPI
5 {
6 ///
7 /// This interface declare the methods need to be implement.
8 ///
9 p
public interface IServiceAPI
10 {
11 v
void CreateNewAccount(s
string firstName, string
12 DataTable GetUserDetails(sstring userName);
13 b
bool UserAuthentication(sstring userName, string
14 DataTable GetDepartmentDetails();
15 }

Next we need to implement declared method in ServiceAPI.cs. Open the

ServiceAPI.cs class. Update the class according to below code. It is
important make all methods public.

2 using System;
3 using System.Data;
4 using System.Data.SqlClient;
6 namespace JSONWebAPI
7 {
9 p
public class ServiceAPI : IServiceAPI
10 {
11 SqlConnection dbConnection;
13 p
public ServiceAPI()
14 {
15 dbConnection = DBConnect.getConnection();
16 }
18 p
public void CreateNewAccount(s
string firstName,
19 {
if (dbConnection.State.ToString() == "Closed"
20 {
21 dbConnection.Open();
22 }
24 s
string query = "INSERT INTO UserDetails VALUES
26 SqlCommand command = new SqlCommand(query, dbCo
27 command.ExecuteNonQuery();
29 dbConnection.Close();
30 }
32 p
public DataTable GetUserDetails(s
string userName)
33 {
34 DataTable userDetailsTable = new DataTable();
35 userDetailsTable.Columns.Add(nnew DataColumn(
36 userDetailsTable.Columns.Add(nnew DataColumn(
38 i
if (dbConnection.State.ToString() == "Closed"
39 {
40 dbConnection.Open();
41 }
43 s
string query = "SELECT firstName,lastName FROM
45 SqlCommand command = new SqlCommand(query, dbCo
46 SqlDataReader reader = command.ExecuteReader();
48 i
if (reader.HasRows)
49 {
50 w
while (reader.Read())
51 {
52 userDetailsTable.Rows.Add(reader[
53 }
54 }
56 reader.Close();
57 dbConnection.Close();
58 r
return userDetailsTable;
60 }
62 p
public bool UserAuthentication(s
string userName,
63 {
64 b
bool auth= false;
66 i
if (dbConnection.State.ToString() == "Closed"
67 {
68 dbConnection.Open();
69 }
71 s
string query = "SELECT id FROM UserDetails WHER
73 SqlCommand command = new SqlCommand(query, dbCo
74 SqlDataReader reader = command.ExecuteReader();
76 i
if (reader.HasRows)
77 {
78 auth = true;
79 }
81 reader.Close();
82 dbConnection.Close();
84 r
return auth;
86 }
88 p
public DataTable GetDepartmentDetails()
89 {
91 DataTable deptTable = new DataTable();
92 deptTable.Columns.Add("no", typeof(String));
93 deptTable.Columns.Add("name", typeof(String));
95 i
if (dbConnection.State.ToString() == "Closed"
96 {
97 dbConnection.Open();
98 }
100 s
string query = "SELECT no,name FROM Dept;"
101 SqlCommand command = new SqlCommand(query, dbCo
102 SqlDataReader reader = command.ExecuteReader();
104 i
if (reader.HasRows)
105 {
106 w
while (reader.Read())
107 {
108 deptTable.Rows.Add(reader["no"], reader
109 }
110 }
112 reader.Close();
113 dbConnection.Close();
115 r
return deptTable;
117 }
118 }
119 }

We have completed the restful API in ASP.NET

Step 6: Run Restful API

In this step you can run the API in a browser. Use the Play (Run) button in
menu bar to run the API or go to DEBUG menu and click Start Debugging
or press F5 from the keyboard. At rst you will see a web page like below. This
is because you are not pointing to the correct page of the API.
To solve this problem simply add /Handler1.ashx to the end of the URL. In
my case complete URL is http://localhost:7541/Handler1.ashx.
Handler1.ashx is the handler of the API. If you used any other name for the
handler in your API use that name instead of Handler1.Then you will see
below webpage

API Main Page

As you can see in the output you can use this restful API with dierent
technologies. But Ill only cover how to use this in android environment. To use
this restful API with Android you need to download the client interface le from
Server. To do that enter ?ANDROID to end of the URL in browser. In my case
URL is http://localhost:7541/Handler1.ashx?ANDROID. Then it will pop up
a Save As dialog box to save the le in your PC. Change the le name to

Save the Client Interface

Step 7: Restful API for Android Part 2

In Restful API for Android Part 2 tutorial Ill show you how to use this restful
API in a client android application. Subscribe to the website through your email
or our social media pages in Google Plus, Facebook, Feed Burner and YouTube
to get instant notication about new tutorials and videos. See the video
demonstration of the tutorial how to do this tutorial from start to end. You can
download the source code of this tutorial below. If you have any questions
related to this tutorial feel free to ask. Comment section is open for you to
communicate with me.

Share this tutorial with your friends and give a support to my website. Thank
you very much for visiting TuteCentral.
Video Demonstration

Download Sample Code

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notications of
new posts by email.

Email Address


Share this:

Google Facebook Twitter More

Ahamed Ishak

I'm a self motivated person who love to learn new stu and share them with others.