Search code examples
phpjsonserverapi-design

Creating an API server with PHP that gets certain data from another api ( Example: api.themoviedb.org)


I am creating an API that is used to get certain data (like certain movies from api.themoviedb.org) and then I need to return this data as a JSON object. I was wondering if anyone had some input on how I could go about this as I am lost.

I understand I need to make a GET request from my api, to the public api, with certain search criteria and obviously an api key. I then need to return this data back to the user that made the search request.

Any suggestions with how to go about this please?


Solution

  • Just design your API as you would normally do, I mean the endpoints, routing, output format, etc.

    For the data retrieval from other network resources you can use:

    <?php
    $postData = 'whatever';
    $headers = [
        'Content-Type: application/json',
        'Auth: depends-on-your-api',
    ];
    $ch = curl_init("http://your-remote-api.url");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    
    // for POST request:
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
    // end for POST request
    
    $response = curl_exec($ch);
    $apiResponseCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    <?php    
    $postData = 'whatever';
    $contextData = [
        'http' => [
            'method' => 'POST',
            'header'=> "Content-type: application/json\r\n"
                . "Auth: depends-on-your-api\r\n",
            'content' => $postData
        ]
    ];
    $response = file_get_contents(
        'http://your-remote-api.url',
        false,
        stream_context_create($contextData)
    );
    

    The links target to specific parts of PHP documentation, that can hint on how to proceed farther.