Web Services using Slim Framework Development
Looking
for some insights to develop your very own exclusive web service ?
Made your mind to create your web service with Slim Framework? We
have got the best answers and solutions for you, through this
article.
What’s
a web service is all about ?
A
web service is nothing but which gives a solid assurance and
protection to your database. It helps a great deal in establishing a
trusted and safe procedure if your database is to be shared with
other applications. One has to come across a lot of problems in the
absence of the web services. Particularly, when you are about to
share your database. This means that you are granting full access to
your database with a potential threat of facing severe consequences
This
is where a web service comes into play nicely. You can create a web
service which will create a real-time scenario in sharing only the
demanded data, not the entire database. Ultimately, this makes a huge
difference.
Slim Framework:
Slim
framework is a dynamic PHP framework which enables you to evolve web
service. It is very distinguished from other set of conventional
methodologies as it proves to be highly time efficient. You can write
your web applications effectively in an uncomplicated manner. It’s
highly responsive as well.
Json
JSON
mediates the transfer of data between applications. In simple words,
it is a lightweight format used for interchanging data effectively.
As the name suggests, it is a subset of Javascript Programming
Language
Develop
your Web Service using Slim
1.
First step is the definition of route. Let’s get started with an
example, when we visit your domain/bikes immediately it will call the
method ‘getBikes’
2.
$app->get('/bikes','getBikes');
Then
we should define our ‘getBikes’ method which will return all the
bikes contained in the Database .To do so , we generate our Sql query
$sql
= "SELECT manufacturer,color FROM bike ORDER BY id";
Then
, execute the query
$db
= getDB();
$stmt
= $db->query($sql);
$Bikess
= $stmt->fetchAll(PDO::FETCH_OBJ);
and
finally return the data as JSON with this line of code
echo
'{"Bikes": ' . json_encode($bikes) . '}';
The
‘getBikes’ method will be :
function
getBikes() {
$sql
= "SELECT manufacturer,color FROM bike ORDER BY id";
try
{
$db
= getDB();
$stmt
= $db->query($sql);
$bikes
= $stmt->fetchAll(PDO::FETCH_OBJ);
$db
= null;
echo
'{"Bikes": ' . json_encode($bikes) . '}';
}
catch(PDOException $e) {
echo "Error !";
}
}
Let’s
test it ! go to the browser and visit yourdomain/bikes , it will show
you this
{"Bikes":[{"manufacturer":"Yamaha","color":"Black"},{"manufacturer":"Honda","color":"Grey"},{"manufacturer":"Bajaj","color":"White"}]}
Conclusion:
For
projects which demands a real-time connection with your databases,
Slim Framework can be used. Simply, because of it’s high degree of
reliability. With several other expected improvisations it's expected
to move only one way and that is forward.