Tuesday, October 04, 2016

Using REST APIs in a web application | Quick PHP Tutorial

in my video on rest api concepts and examples i showed you how to get the
latitude and longitude for any location using the google maps api and then pass
those coordinates to the instagram api to receive pictures taken at that
location
so in this video I'm going to walk you quickly through building that
functionality into a simple web application
so here's what we'll be building we have a page with a single input field where
you can enter a location say disneyland california and then we click Submit and
the page reloads and a list of Instagram images from disneyland or display cool
stuff
let's dive into the code and see how this is put together i'll be doing this
in a single PHP file which will contain all of our application logic as well as
our view and you can find a link to the finish PHP file in the description below
of course in a real world application you're going to be using a framework
along with its controllers and templates so that one file you have dozens but for
simplicity bear with me on this single file nonsense
also i'll be doing this in PHP but there's no reason why you couldn't do it
in Python or Ruby or pure JavaScript or any programming language that's capable
of making HTTP requests
so let's get to it for starters let's create the PHP file and sense everything
needs a name will call it geo Graham dot PHP opening it up
let's add an opening and closing PHP tag to the top of the file which is where we
will add our application logic will get back to that in just a minute
below that let's put a very basic html5 boilerplate and as you can see I've only
added a title of geographic to the head section and left the rest of the HTML
body blank
now we load this page in the browser and its current state you can see it's blank
of course a little PHP file on your browser you're going to be running a web
server of some sort on your machine
in this case I'm running apache and i'm serving this file at localhost / 30 gram
dot PHP going back to the code now let's add our for mark up to the HTML body as
a quick refresh for those like me who haven't worked with raw HTML forms in a
while the forms action attribute tells the browser where to submit the form
however if you leave it blank then it will submit the form to the address of
the current page which is what we want in this case since our application is
only this one PHP file next ones that are input tag making sure the type
attribute is set to text and we'll also add a name attribute to the input and
we'll set its value as location
finally well our button since the button is inside of the form giving it a type
attribute of submit will submit the form of the buttons click course if you need
the button to be outside of the four
you could always use JavaScript to submit the form as well so let's go
ahead and reload the page in our browser and you can see our location input form
and submit button and if we type test and click Submit you can see that up in
the URL bar the form was submitted to the same location
localhost / g gram . PHP and we see that the query parameter location has been
added
remember that was the name that we gave our input tag in HTML markup and of
course its value is test
ok with that painful HTML form of pressure out of the way let's write our
application logic by and we'll first move this HTML down on the way to keep
your mind focused on PHP for a minute
first thing we need to do is grab the location parameter that sent to the
server from the web browser now when a PHP file is initialized by a web server
a whole bunch of information about the HTTP request is loaded into special PHP
variables query parameters contain is part of a get request are put in the
gate array
so in this case the location value entered in the form will be contained in
the location key in the gate array and because we only want to make our API
request if the location has been submitted will wrap our application
logic in a conditional to check whether the getlocation key is set and if not
then we'll skip over all of our PHP and simply load the HTML form that we've
already added below
so now comes the fun part let's send that location over to the google maps
api to get its geo coordinates now again if this were a real application you
probably want to use some kind of library to make the cpa request but
since we're making a simple get request to a REST API will just use PHP file get
contents function i showed you in my rest api video that the google maps api
can be accessed at maps google api calm / maps / AP I / geocodes last Jason and
then you said what you want to search for under the address parameter so we
set our Maps URL variable equal to that URL string and then will concatenate our
location variable the get location after the equal sign
final pass the maps are all variable to the file get contents function and
capture the return into our maps
Jason variable but let's load that up into the browser and see what the
response looks like before we look at the response though
that's what happens when I add a space to the URL google maps api still returns
a valid response however see how the space was replaced automatically with
percent 20
that's because an HTTP URL containing spaces is invalid with your browser is
doing automatically is URL encoding those invalid characters
however when programming something
you need to do this yourself so let's go back to the code real quick and we'll
wrap our location variable in the URL and code function so now let's go back
to that response again in the browser and you see that what's return is Jason
data before we can work with this response from the google maps api we
need to convert that Jason into a PHP array to do this will pass the Jason
response received from the file get contents to PHP is Jason decode function
will set the second parameter the true so that the Jason is decoded into an
array as opposed to an object and will capture this return into a variable
simply called maps array
ok back to getting our data from the google maps api looking one more time at
the Jason response in the browser we can see that the data were interested in is
contained under the lat and lang values all the way down here now because the
PHP array will maintain the same structure as the original Jason response
will traverse the maps array variable to get those values so working backwards we
see that the data that we want is under the key location and then the key
geometry and then an array value which will have an American zero sense the
first member of the array and finally the key results
putting it together in our PHP or lat will be contained under the maps are a
results 0 geometry location lat and longitude of the intermatter a results 0
geometry location lng so to make things easier to re going forward let's pull
each of those values into a lat and laying variable
now that we have our coordinates let's pass them to Instagram
now if you recall in my rest api video I showed you that you can search
instagram by location using the following API endpoint api .
instagram.com so I should be 1 / media / search with the following parameters lat
lang and client ID know that we're using the primary client ID rather than an
access token you can use either it's totally up to you
so we'll go ahead and set our Instagram URL as API dance around a calm / if you
want / media search and then we'll set the lat equal to the lat variable we
captured from google maps and the laying variable equal to the Lang variable we
got from google maps and then this will be our client ID
no I'm going to delete this client before i post the video you're gonna
have to create your own in the Instagram developer dashboard for your reference i
cover how to do this at the beginning of my video on Jay
rating Instagram access tokens ok so just like the Google Maps API will pass
this Instagram URL variable to the file get contents function and get back Jason
data again we want to decode the Jason data into a PHP array and we'll name the
variable that captures it
instagram array so opening up the Instagram URL in the browser we can see
that the response contains a key called images with URLs two different image
sizes will be using the low-resolution image in our application so working
backwards we see that the URL value we want is under URL low-resolution images
on a Reiki and finally data
notice that when we collapse the array key for that image we see another image
entry below it
in fact this API requests returned 20 separate Instagram posts all contained
as members of the data array so to pull the low-resolution URLs from each of the
20 Instagram post
we want to write out 20 separate lines of code instead we'll run the Instagram
array data through a loop since the day that we want the low-resolution URL is
in the same place in every Instagram post and since we want to display these
images in our view let's head back down to the HTML markup set a break and then
an opening and closing pair of PHP tags within which will put our for each loop
written in PHP it looks like this for each Instagram array data as image
what this does is that as the for each loop is going through the list of
Instagram post it says the image variable equal to a single Instagram
post that way we can process it further
of course this is only temporary as that variable is replaced by the next
Instagram post on the subsequent loop and since there's 20 Instagram posts
contained in our a everything that we program inside this for each loop will
be executed 20 times once for each Instagram post
so we'll do inside of the for each loop is echo and HTML image tag and we'll set
the image source equal to the value of image and then the key low resolution
and finally the key URL and this will echo out 20 image tags in total
one for each of the Instagram post one last thing we need to add is conditional
wrapper around the for each loop since we don't want to attempt to echo any
images
unless we've successfully received them from the instagram api otherwise we'll
get errors when loading the page
so let's go ahead and refresh our geo Graham dot PHP page in the browser and
once again in our disneyland california
click Submit and boom it works so there you have it that wasn't too difficult
right of course if you have any experience programming
you'll notice that there's tons of stuff missing things like styling or catching
error handling and even making the request over Ajax would really enhance
the application so be sure to subscribe i'll be going over some of those
concepts in future videos and adding them to this little geograph application
if you have any questions hit me up in the comments or on twitter at been beard
trim
thanks so much for watching and I'll see you guys next time

No comments:

Post a Comment