Consuming ASP.NET Web API services from PHP script
I introduced ASP.NET Web API in some of my previous posts. Although Web API is easy to use in ASP.NET web applications you can use Web API also from other platforms. This post shows you how to consume ASP.NET Web API from PHP scripts.
Here are my previous posts about Web API:
- How content negotiation works?
- ASP.NET Web API: Extending content negotiation with new formats
- Query string based content formatting
Although these posts cover content negotiation they give you some idea about how Web API works.
Test application
On Web API side I use the same sample application as in previous Web API posts – very primitive web application to manage contacts.
Listing contacts
On the other machine I will run the following PHP script that works against my Web API application:
// request list of contacts from Web API
$json = file_get_contents('http://vs2010dev:3613/api/contacts/');
// deserialize data from JSON
$contacts = json_decode($json);
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<table>
<?php
foreach($contacts as $contact)
{
?>
<tr>
<td valign="top">
<?php echo $contact->FirstName ?>
</td>
<td valign="top">
<?php echo $contact->LastName ?>
</td>
<td valign="middle">
<form method="POST">
<input type="hidden" name="id"
value="<?php echo $contact-/>Id ?>" />
<input type="submit" name="cmd"
value="Delete"/>
</form>
</td>
</tr>
<?php
}
?>
</table>
</body>
</html>
Notice how easy it is to handle JSON data in PHP! My PHP script produces the following output:
Looks like data is here as it should be.
Deleting contacts
Now let’s write code to delete contacts. Add this block of code before any other code in PHP script.
if(@$_POST['cmd'] == 'Delete')
{
$errno = 0;
$errstr = '';
$id = @$_POST['id'];
$params = array('http' => array(
'method' => 'DELETE',
'content' => ""
));
$url = 'http://vs2010dev:3613/api/contacts/'.$id;
$ctx = stream_context_create($params);
$fp = fopen($url, 'rb', false, $ctx);
if (!$fp) {
$res = false;
} else {
$res = stream_get_contents($fp);
}
fclose($fp);
header('Location: /json.php');
exit;
}
Again simple code. If we write also insert and update methods we may want to bundle those operations to single class.
Conclusion
ASP.NET Web API is not only ASP.NET fun. It is available also for all other platforms. In this posting we wrote simple PHP client that is able to communicate with our Web API application. We wrote only some simple code, nothing complex. Same way we can use also platforms like Java, PERL and Ruby.