Search code examples
phprestapisliminternals

Slim Framework : Call internal API REST


I've created API REST collections on my project that will be called both internally (in the same PHP project) and externally (from other projects)

My question is : What is the best way to consume internal API REST ?

I've created a function to mock the call this way :

        // init mock 
        $env = Environment::mock([
            'REQUEST_METHOD'     => 'GET',
            'REQUEST_URI'        => $path,
            'QUERY_STRING'       => $urlParams,
            'HTTP_AUTHORIZATION' => 'Bearer '.$token
            ]);
        $req = Request::createFromEnvironment($env);

        // Instantiate CandidateRoute
        $app = (new $class)->get();
        $app->getContainer()['request'] = $req;
        // Run slim inst
        ob_flush();
        // Run Slim
        $response = $app->run(true);

This is working, but it's still an HTTP call in the end...

  • Any other way to consume internally API REST ?

  • Is better to call through CURL instead of mocking ?

  • Is it OK to make many HTTP calls for API REST that are in the same project ? (I guess no)

Thanks in advance!


Solution

  • Based on Slim documentation : http://www.slimframework.com/docs/v3/cookbook/environment.html

    Mock Environment objects are only useful when writing unit tests.

    This rules out using mock on production, which means I'll have to consume internal APIs using cURL. I kept my function for PHPUnit tests.

    I've decided to add a callApi() function that sends GET/POST/PUT cURL requests as if the API is external, since I couldn't find any better solution... I still have a problem with the 414 Request-URI Too Long when using GET, but that will be for another topic.