How to build a RESTful API?

前端 未结 7 1694
广开言路
广开言路 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:13

    Here is a very simply example in simple php.

    There are 2 files client.php & api.php. I put both files on the same url : http://localhost:8888/, so you will have to change the link to your own url. (the file can be on two different servers).

    This is just an example, it's very quick and dirty, plus it has been a long time since I've done php. But this is the idea of an api.

    client.php

    
        
    Name:
    First Name:
    Age:
    Return to the user list

    api.php

     "Marc", "last_name" => "Simon", "age" => 21); // let's say first_name, last_name, age
          break;
        case 2:
          $user_info = array("first_name" => "Frederic", "last_name" => "Zannetie", "age" => 24);
          break;
        case 3:
          $user_info = array("first_name" => "Laure", "last_name" => "Carbonnel", "age" => 45);
          break;
      }
    
      return $user_info;
    }
    
    function get_user_list()
    {
      $user_list = array(array("id" => 1, "name" => "Simon"), array("id" => 2, "name" => "Zannetie"), array("id" => 3, "name" => "Carbonnel")); // call in db, here I make a list of 3 users.
    
      return $user_list;
    }
    
    $possible_url = array("get_user_list", "get_user");
    
    $value = "An error has occurred";
    
    if (isset($_GET["action"]) && in_array($_GET["action"], $possible_url))
    {
      switch ($_GET["action"])
        {
          case "get_user_list":
            $value = get_user_list();
            break;
          case "get_user":
            if (isset($_GET["id"]))
              $value = get_user_by_id($_GET["id"]);
            else
              $value = "Missing argument";
            break;
        }
    }
    
    exit(json_encode($value));
    
    ?>
    

    I didn't make any call to the database for this example, but normally that is what you should do. You should also replace the "file_get_contents" function by "curl".

提交回复
热议问题