How to build a RESTful API?

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

    (1) How do I ... build those URI's? Do I need to write a PHP code at that URI?

    There is no standard for how an API URI scheme should be set up, but it's common to have slash-separated values. For this you can use...

    $apiArgArray = explode("/", substr(@$_SERVER['PATH_INFO'], 1));
    

    ...to get an array of slash-separated values in the URI after the file name.

    Example: Assuming you have an API file api.php in your application somewhere and you do a request for api.php/members/3, then $apiArgArray will be an array containing ['members', '3']. You can then use those values to query your database or do other processing.

    (2) How do I build the JSON objects to return as a response?

    You can take any PHP object and turn it into JSON with json_encode. You'll also want to set the appropriate header.

    header('Content-Type: application/json');
    $myObject = (object) array( 'property' => 'value' ); // example
    echo json_encode($myObject); // outputs JSON text
    

    All this is good for an API that returns JSON, but the next question you should ask is:

    (3) How do I make my API RESTful?

    For that we'll use $_SERVER['REQUEST_METHOD'] to get the method being used, and then do different things based on that. So the final result is something like...

    header('Content-Type: application/json');
    $apiArgArray = explode("/", substr(@$_SERVER['PATH_INFO'], 1));
    $returnObject = (object) array();
    /* Based on the method, use the arguments to figure out
       whether you're working with an individual or a collection, 
       then do your processing, and ultimately set $returnObject */
    switch ($_SERVER['REQUEST_METHOD']) {
      case 'GET':
        // List entire collection or retrieve individual member
        break;
      case 'PUT':       
        // Replace entire collection or member
        break;  
      case 'POST':      
        // Create new member
        break;
      case 'DELETE':    
        // Delete collection or member
        break;
    }
    echo json_encode($returnObject);
    

    Sources: https://stackoverflow.com/a/897311/1766230 and http://en.wikipedia.org/wiki/Representational_state_transfer#Applied_to_web_services

提交回复
热议问题