PHP web based API design and Calling API from ASP .net

1. PHP API:

<?php
// http://localhost:8080/api/index.php?FORM_NO=100001&PASSWORD=abcde&EMAIL=nazim@kuet.ac.bd&NAME=Md. Nazim Uddin
$FORM_NO = 0;
$PASSWORD = “”;
$EMAIL = “”;
$NAME = “”;

try{
$FORM_NO = $_GET[‘FORM_NO’];
$PASSWORD = $_GET[‘PASSWORD’];
$EMAIL = $_GET[‘EMAIL’];
$NAME = $_GET[‘NAME’];
}catch(Exception $ex){}

if($FORM_NO != 0 AND $PASSWORD != “”)
{
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user ‘root’ with no password) */
$link = mysql_connect(“localhost”, “root”,”19831021″);
// make foo the current db
$db_selected = mysql_select_db(‘api’, $link);
if (!$db_selected) {
die (‘Can\’t use api : ‘ . mysql_error());
}
// Attempt insert query execution
$sql = “INSERT INTO CANDIDATE (FORM_NO, PASSWORD, EMAIL, NAME) VALUES (“.$FORM_NO.”, ‘”.$PASSWORD.”‘, ‘”.$EMAIL.”‘, ‘”.$NAME.”‘)”;
//mysql_query($sql);
try{
if(mysql_query($sql)){
//echo “Records added successfully.”;
_response(200,”<replay>1</replay>”);
} else{
//echo “ERROR: Could not able to execute $sql. ” . mysql_error($link);
_response(200,”<replay>0</replay>”);
}
}catch(Exception $e)
{
_response(200,”<replay>0</replay>”);
}

// Close connection
mysql_close($link);
}

function _response($status, $response)
{
header(“HTTP/1.1 ” . $status . ” ” . $response);
return json_encode($response);
}

?>

2. ASP.net Calling:

Int32 IsFailed = 0;
try
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(“http://localhost:8080/&#8221;);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(“application/json”));
HttpResponseMessage response = client.GetAsync(“api/index.php?FORM_NO=100008&PASSWORD=csdeam2&EMAIL=nazim@kuet.ac.bd&NAME=Laboni Serker”).Result;

try
{
if (response.IsSuccessStatusCode)
{
if (response.ReasonPhrase.Contains(“<replay>1</replay>”))
{
String Success = “1”;
IsFailed = 0;
}
/*
* response contains the:
* Content
* Headers
* IsSuccessStatusCode
* ReasonPhrase (json request-> json response)
* RequestMessage
* StatusCode
* Version etc.
*/
}
else
{
//Something has gone wrong, handle it here
if (response.ReasonPhrase.Contains(“<replay>0</replay>”))
{
String Success = “0”;
IsFailed = 1;
}
}
}
catch (Exception excp) { }
}
catch (Exception ex) {  }

We get the API operation is success or not as JSON response by using ASP .net’s ReasonPhrase (json request-> json response)

Hope this will healp others

Good Luck !!!!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s