How to use a REST API from PHP using cURL | Full PHP cURL API tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in this video we're going to learn how to use curl from php to interact with a restful api we'll be using the github rest api and we'll learn how to create read update and delete repositories using this api from php so let's create a new file called index.php and we'll add the php opening tag we'll start by calling the curl init function to initiate a curl session we'll start by using the api to get a list of repositories for the authenticated user which we do by making a get request to slash user repos on the api.github.com host so we'll pass the url of this endpoint to the curl init function this returns a handle to the curl session so we'll assign that to a variable to send the request we call the curl exec function passing in this variable finally we'll call the curl close function to close the session and free up any resources let's give that a try when we open this page in a browser we get a message saying the request was forbidden because it lacked a user agent header the github api requires that all api requests include a valid user agent header this can be your github username or the name of your application to add a header to the request first let's create a variable called headers which contains an array we'll add a string element to this array which contains the string user agent followed by a colon and the value of the header for which i'll put the name of this application to attach this to the request we call the curlset opt function passing in the curl handle the curl opt http header constant and the headers variable let's give that a try and now we get a message that the request requires authentication to authenticate requests to this api you need an access token you can create an access token in the personal access token section in the developer settings of your github account when you create a token make sure it has full access to create read update and delete repositories the account i'm using already contains a couple of repositories to authenticate the request we send the access token in a request header so let's add another value to the array of headers with the name authorization followed by a colon the word token as we're using token authentication followed by the value of the token for now let's input an invalid token to see what happens now when we make the api request we get a message that says bad credentials so if you see this message the access token value is incorrect let's change this to the valid access token and now we get a valid response and we see the data for the repositories in this account the api returns this data in json format it might look complex but it's basically just a series of key and value pairs as we'll see in a moment we can easily decode this in php so we can access specific values first though in order to process this data we need access to it you might have noticed that at no point in this code are we using echo or any other operator to output the response when we execute the curl request the response is just sent directly to the browser to avoid this we set the return transfer option to true this means the response body will be returned as a string when we call the curl exec function before doing anything with this return value with this option set if we run the code again nothing is output in the browser if we assign the return value of the curl exec function call to a variable then output that variable using vardump now we get the response body again which is a string containing the json formatted data to decode this data we use the php json decode function passing in the string containing the json let's print out the return value from this to see what it contains when we run this we get an array with two elements each element is a php object where the property names and their values correspond to the attributes of the repositories if we pass true as the second argument to the json decode function then instead of objects we get associative arrays now we have this data in a format we can use instead of just outputting the whole array we'll just output some specific attributes first let's loop around the array of results as we just saw each element of this array is an associative array of all a repository's attributes let's just print out the full name name and description attributes let's also add a space between each of these and an html line break element at the end just so that we can see the attributes more clearly in the browser now we just get those attributes printed out for the two repositories in this account now we've extracted these individual data items out we can add some formatting with html and css so let's comment out this loop for now and add the php closing tag to end this php block then we'll add some html the doctype and html tag a head section with a title and a body element inside the body we'll add a header and we'll display the list of repositories in a table so let's add a table tag with a t-head element containing the column headers we'll have a column for the repository name and one for the description then let's add a t-body element in here we want to display one table row for each repository so let's add a for each loop as we did above and inside the loop we'll add a table row element containing two table data elements one for the repository name and one for the description as the repository name is used in urls this is restricted to url safe characters but the description isn't so it could contain any characters so just to be safe we'll add a call to the html special charts function to escape any of those characters that might be in the description in the browser now we have a title and the data are displayed in a table with one row for each property and the titles at the top of each column to add some styling to this let's use the pico css framework this is a minimal css framework that adds styling without having to add classes to html elements we can add the stylesheet from a cdn so we don't even have to download anything so let's copy this line and paste it in the head section of the html so the styles are applied properly we need to add a container element so we'll add a main element around the body content in the browser now the content has some nice styling and is centered nicely in the viewport now we have an index of all the repositories let's add a script to get the details of an individual one to get the details of an individual repository we make a get request to this endpoint slash repos then the owner and repository name the owner and repository name are available in the full name attribute of the repository so we can use this value to uniquely identify a repository we'll add a new file to show the details of an individual repository but before we do that let's add a link to it from this index file we'll call the script show.php and pass the full name attribute in the query string now we can delete this commented out code where we were originally displaying the repository data now we can create the show.php script as the index file already has lots of the code we'll need for this we'll start by making a copy of this file and save it as show.php the first thing we'll do in here is to get the value we're using to identify the repository from the query string which will be in the get super global then we can change the end point we're making the request to to the one for getting an individual repositories details including the value from the query string the rest of the curl code will be the same we'll remove this duplication in a moment down in the html let's change the header to just repository and remove the html table entirely instead we'll display the repository details using a description list element with term elements for the name and description with corresponding definition elements this time the data variable contains an associative array for a single repository so we can access its elements directly for the description let's not forget to add a call to the html special charts function as we did in the index let's give that a try on the index page now each repository's name is a link if we click on one of those links we're taken to the show page where we can see the details of the individual repository there are of course many more attributes you could show here but we'll just keep it simple and show these two note the full name of the repository has been passed in the query string a lot of the curl code at the top of the show page is the same as the index page before we add any more pages let's remove this duplication in both pages we're creating a curl session passing in the endpoint url then setting options to send headers and return the response body as a string instead of passing in the endpoint url when we call the curl init function let's set this as an option instead which we do with the curl opt url constant let's do the same in the index page setting the url as an option instead of passing it to the curl init function now we can extract out this common code to another file so let's copy this code and create a new file called init curl.php we'll add the php opening tag and paste the code in here so in this script we're creating a curl session setting these common options and finally let's add a return statement to return the variable containing the curl handle from this script back in the index we can now replace this code we just extracted by requiring the new script and assigning the return value from this statement to a variable this is just so that it's clear in this script where the variable is coming from in the show page we can do the same removing these lines of common code and require the scripts we just added assigning its return value to a variable let's check that still works and the index and show pages work as before if you're setting several curl options by calling the curl set opt function like this there is an alternative way of setting them and that's to use the curl setup to ray function instead of one function karl per setting you just pass an array of settings and their values to the curl setup to ray function like this you can use whichever method you prefer and even use both want to set some settings and the other to set others it's up to you let's also just quickly remove the duplication in the html this code is repeated in both pages so let's copy this then create a new file called header.html we'll paste the code in here then in the index file we can replace this code with a require statement including the new file in the shell page we can do the same remove the duplicated html and add the require statement we'll do the same for the html at the end so let's copy this create a new file called footer.html and paste the code in there back in the show.php script we can remove this code we just copied and require the footer.html file and in the index.php script we can do the same in the browser both pages still work as before next let's add code to create a new repository to do this we send a post request to slash user repos note that this is the same end point we use to get a list of repositories to create a new repository however we use the post request method instead of get let's start by creating a new file called new.php this will contain the form where we input the data for the new repository now that we have the html header and footer in separate files we can quickly create a new file so let's include the header file then we'll add a heading element we'll add a form that uses the post method then inside the form let's add a text input for the repository name called name and an associated label for the repository description we'll add a text area element again with an associated label as with the other pages so far there are many more attributes that you could add here but we'll keep it simple and just have these two finally we'll add a button to submit the form at the end of the page let's include the footer before we view this in the index page let's add a link to this new page in the browser there's the link to the new page and there's the form with inputs for the name and description and the submit button now we can add a file to process this form when it's submitted instead of doing this in the same script let's add a new file to do this and call it create.php in here we want to make a request to the same endpoint as the index page so let's copy this code from the top of that page and paste it in the create script in this script however we want to send the request using the post request method along with the data from the form there are multiple ways you can do this first let's set the post option to true this will set the request method to post to send the data from the form we set the post fields option and we'll just set this to the data from the form directly which will be the contents of the post array another way to set the request method to post is to set the custom request option to the uppercase string post you can use either one of these but there's also a third way by setting the post fields option this automatically sets the request method to post so you don't actually have to explicitly do it but you can if you prefer to see what happens when we try that let's use vardump to print out the response body before we try that we have to link the form to the create script by adding an action attribute to the form tag let's give that a try first let's try submitting an empty form we get an error message saying problems passing json just as the data returned from the api is formatted as json the data we send to this api has to be formatted as json also to do this we'll call the json code function on the post array let's try that again still leaving the form empty for now we get a message saying repository creation failed the problem is that there are validation errors on the data basically in this case the name field is required but we submitted an empty value to detect this we could check this json to see if it has an errors element but a better way is to check the response status code to check the status code we call the curl get info function passing in the curl handle and the response code constant there are various response codes that can be returned by this endpoint if the validation fails we get a 422 unprocessable entity response so after we've closed the curl handle let's check for that and if the status code is 422 we'll just print out a message and the contents of the errors element of the array then we'll exit the script so now if we submit an empty form we get the message and the validation error details what you'd probably do in practice here is redirect back to the form displaying error messages along with the original data r have some equivalent client-side validation using javascript to keep it simple though for the purposes of this demonstration i'm going to leave it like this if the repository is created and we get a successful response we get a 201 status code with some json in the body of the response with the data of the repository that was created again to keep it simple let's add a check for any other status code and if it's not 201 we'll just print it out and move this var dump line into this block and exit the script if it is 201 the repository was created successfully so let's output a useful message to the user we'll add the php closing tag then include the header file and an html header element let's output a message that says the repository was created successfully and as the response body contains the details of the repository we can provide a link to the show page passing in the full name attribute from the data in the query string finally we'll include the footer file let's give that a try if i enter some data into the form when i submit it we get the message saying the repository was created successfully and we have a link to the shell page where we can view the repository details next let's add functionality to edit an existing repository let's start by displaying a form containing the repository's current attributes in the show page we're getting the repository based on the full name in the query string and displaying some of these details in the body of the html so let's start by making a copy of this file calling it edit.php and we'll change the content of the header element accordingly instead of displaying the repositories attributes in a description list we'll use a form let's copy the form from the new script and paste it in the edit script when this form is displayed for creating a new repository the fields are initially empty for editing however we need to display the existing values so let's add a value attribute to the name input containing the name element from the data array which we'll copy from the description list likewise for the description we'll copy the value for the description and paste this inside the text area element now we can remove the description list before we try this let's add a link to this page from the show page passing in the full name attribute of the repository in the query string in the browser there's the link to the edit page and on that page we see the form with the inputs containing the repository's existing values next let's add a page to process this form when it's submitted we're doing something similar in the create.php script so let's start by making a copy of this file and naming it update dot php to update a repository we send a patch request to slash repos followed by the full name of the repository so the first thing we need to do is pass the full name from the edit script where the form is to this update script where it's submitted to so in the edit script inside the form let's add a hidden field called full name that contains the value of the full name from the data while we're here let's also change the action parameter of the form element to update.php in the update script to get the correct endpoint we'll get the value of the full name from the request which as the form is using post will be in the post array we won't sanitize this value as it's beyond the scope of this example but it's probably a good idea to do so as we're inserting it directly into the url we're calling to set the request method to patch we need to set the custom request option making sure we put the method in uppercase setting the request body and acting on a 422 status code for validation errors will be the same however if the request is successful we get a 200 status code instead of a 201 so we'll change that in this if condition in the html we'll change the content of the header element and the message shown if the repository is updated successfully let's give that a try if i make some changes to the data and submit the form we're shown the message saying the repository has been updated and the link takes us to the show page for that repository next let's add functionality to delete an existing repository the code to do this will be similar to the update script so let's start by making a copy of this and calling it delete.php to delete a repository we send a delete request to the same endpoint as updating your repository so in the delete script we'll keep the part where we set the url from the value in the post request but we'll change the request method to delete making sure we specify it in uppercase we don't need to send any data in the body of the request so we can remove this line if the repository is deleted successfully the response will contain a 204 status code so we can remove the code that checks for invalid data as we're not sending any and change this if condition to check for it not being 204 if all is well we'll change the html that's displayed to have a different header a different message and a link back to the index page as with the edit page we'll add a link to the delete page from the show page however as we want to send this as a post request we'll do it using a form so we'll add a form that uses the post method that submits to the delete.php script inside this form we need to send the full name attribute of the repository which we'll do in a hidden field we'll add a delete button and close the form there are other ways you could do this using javascript for example to send a post request with a regular anchor tag and it's probably a good idea to have some kind of confirmation message before the repository is deleted but for the purposes of this demo we'll keep it simple in the browser on the show page there's the button to delete the repository note that as soon as i click this the repository will be deleted without confirmation so be careful if you're using an account you don't want to delete repositories from if i click it we get the message saying this repository was deleted and we're shown the link back to the index page where we can see the repository has been deleted so with this code you can retrieve create edit and delete repositories using the github api using curl from php the full code developed in this video is available in this repository on github and the link to this is in the description please don't forget to like comment and subscribe and as always thank you for watching
Info
Channel: Dave Hollingworth
Views: 721
Rating: undefined out of 5
Keywords:
Id: rQqR-gKBBz0
Channel Id: undefined
Length: 31min 8sec (1868 seconds)
Published: Fri Dec 03 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.