How to build a RESTful API?

前端 未结 7 1646
广开言路
广开言路 2020-11-27 09:43

The issue is this: I have a web application that runs on a PHP server. I\'d like to build a REST api for it.
I did some research and I figured out that REST api uses HTT

相关标签:
7条回答
  • 2020-11-27 10:22

    That is pretty much the same as created a normal website.

    Normal pattern for a php website is:

    1. The user enter a url
    2. The server get the url, parse it and execute a action
    3. In this action, you get/generate every information you need for the page
    4. You create the html/php page with the info from the action
    5. The server generate a fully html page and send it back to the user

    With a api, you just add a new step between 3 and 4. After 3, create a array with all information you need. Encode this array in json and exit or return this value.

    $info = array("info_1" => 1; "info_2" => "info_2" ... "info_n" => array(1,2,3));
    exit(json_encode($info));
    

    That all for the api. For the client side, you can call the api by the url. If the api work only with get call, I think it's possible to do a simply (To check, I normally use curl).

    $info = file_get_contents(url);
    $info = json_decode($info);
    

    But it's more common to use the curl library to perform get and post call. You can ask me if you need help with curl.

    Once the get the info from the api, you can do the 4 & 5 steps.

    Look the php doc for json function and file_get_contents.

    curl : http://fr.php.net/manual/fr/ref.curl.php


    EDIT

    No, wait, I don't get it. "php API page" what do you mean by that ?

    The api is only the creation/recuperation of your project. You NEVER send directly the html result (if you're making a website) throw a api. You call the api with the url, the api return information, you use this information to create the final result.

    ex: you want to write a html page who say hello xxx. But to get the name of the user, you have to get the info from the api.

    So let's say your api have a function who have user_id as argument and return the name of this user (let's say getUserNameById(user_id)), and you call this function only on a url like your/api/ulr/getUser/id.

    Function getUserNameById(user_id)
    {
      $userName = // call in db to get the user
      exit(json_encode($userName)); // maybe return work as well.
    }
    

    From the client side you do

        $username = file_get_contents(your/api/url/getUser/15); // You should normally use curl, but it simpler for the example
    // So this function to this specifique url will call the api, and trigger the getUserNameById(user_id), whom give you the user name.
        <html>
        <body>
        <p>hello <?php echo $username ?> </p>
        </body>
        </html>
    

    So the client never access directly the databases, that the api's role.

    Is that clearer ?

    0 讨论(0)
提交回复
热议问题