Make API calls from phalcon to another API

Hi, I'am new to this framework and I was wondering for a project if it was possible to make API calls from phalcon to another API. I found some interesting stuff here https://docs.phalcon.io/4.0/en/http-server-request but I don't understand how to use it and if it can help me.



7.8k
edited 7d ago

Phalcon\Http\Message\ServerRequest is an implementation of the PSR-7 HTTP messaging interface as defined by PHP-FIG.

as i understand basicly it creates everything (in form of an object) except the request itself and for that you would need a PSR-7 compliant client to pass this object to complete your request

i could be wrong for all i care but unless you really want the request to be server side for any reason i would throw this request to be done client side

Phalcon\Http\Message\ServerRequest is an implementation of the PSR-7 HTTP messaging interface as defined by PHP-FIG.

as i understand basicly it creates everything (in form of an object) except the request itself and for that you would need a PSR-7 compliant client to pass this object to complete your request

i could be wrong for all i care but unless you really want the request to be server side for any reason i would throw this request to be done client side

Hi, thank you for your response. I'm currently working on a project where my phalcon app will receive API calls, treats those and then makes API calls in consequence to another API. That's why I thought that I should make those API calls server side. I don't know if it's the best way to do this, but I'm open to suggestions.



7.8k

check https://github.com/guzzle/guzzle

you can use Phalcon's implementation of the PSR-7 HTTP messaging with guzzle's client

example

use Phalcon\Http\Message\ServerRequest;
use Phalcon\Http\Message\Uri;
use GuzzleHttp\Client;

$uri = new Uri('http://jsonplaceholder.typicode.com/posts');

$request = new ServerRequest();

$request = $request
    ->withHeader('Content-Type', ['application/json'])
    ->withMethod('POST')
    ->withUri($uri)
    ->withParsedBody([
        'title' => 'foo',
        'body' => 'bar',
        'userId' => 1001,
    ]);

$client = new Client;

$response = $client->send($request); // GuzzleHttp\Psr7\Response

$body = $response->getBody(); // GuzzleHttp\Psr7\Stream

$contents = $body->getContents(); // string { "id": 101 }

javascript equivalent:

fetch('http://jsonplaceholder.typicode.com/posts', {
  method: 'POST',
  body: JSON.stringify({
    title: 'foo',
    body: 'bar',
    userId: 1001,
  }),
  headers: {
    'Content-type': 'application/json; charset=UTF-8',
  },
})
  .then((response) => response.json())
  .then((json) => console.log(json))

you can also check https://github.com/php-curl-class/php-curl-class