How to make a proper API call with Symfony?

I’m just getting into the Symfony framework and trying to make a simple API call to an external source.
I am not aware of what are the good practices and how to deal with this in an elegant way, so I am very thankful for any feedback.

This is my Controller:

namespace AppController;

use AppDeutscheBankAPICaller;
use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentRoutingAnnotationRoute;
use SymfonyContractsHttpClientHttpClientInterface;

class MainController extends AbstractController
{
/**
 * @Route("/main", name="main")
 */
public function index(Request $request, HttpClientInterface $client): Response
{

    $api_caller = new DeutscheBankAPICaller($client);
    echo $api_caller->get_authorisation_code();

    return $this->render('main/index.html.twig', [
        'controller_name' => 'MainController',
    ]);
}

And this is the API caller class:

namespace App;


use SymfonyContractsHttpClientHttpClientInterface;

class DeutscheBankAPICaller
{
private $client_id = "MYCLIENTID";
private $secret_key = "MYSECRETKEY";
private $redirect_uri = "https://localhost:8000";
private $authorisation_url = "https://simulator-api.db.com/gw/oidc/authorize";

public function __construct(HttpClientInterface $client)
{
    $this->client = $client;
}

public function get_authorisation_code() {
    $response = $this->client->request(
        'GET',
        $this->authorisation_url,
        [
            'query' => [
                'response_type' => 'code',
                'redirect_uri' => $this->redirect_uri,
                'client_id' => $this->client_id,
            ]
        ]
    );

    return $response->getContent();
}

}

When I try to execute this, I get (correctly) redirected to the login form of the API provider. After submitting the login data though, I get an error from the API provider saying "Could not verify the provided CSRF token because your session was not found." Refreshing the site (and submitting the data again) results in the message "Invalid CSRF Token ‘foo-bar’ was found on the request parameter ‘_csrf’ or header ‘X-CSRF-TOKEN’".

Now for interesting part: after typing the URL manually in an incognito window and submitting the login data, it all works correctly and I get the desired response.

Why is that happening? How does the HTTP client request differ from my manual request? And how can I fix this?

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *