whitebear
whitebear

Reputation: 12455

Access rest API from inside controller and from twig

I made API by api-platform , the generated url is like this below. (I have Product entity)

/api/product?id=3

This routing api is generated by api-platform. So I don't know the name of routing.

Now, I want to access this API from both twig file and Controller.

1) In twig, it should be like this below, but where I can find routing name??

{{path('***')}}/product?id-3

2) In Controller how can I access the API??

Is there any help??

My environment is Symfony 4.1, php 7.1

Upvotes: 1

Views: 2461

Answers (1)

dbrumann
dbrumann

Reputation: 17166

Your api route has a name in Symfony, this is what you should use inside path. You can find it by using the debugging tools provided by symfony, e.g.:

bin/console router:match "/api/product?id=3"

This should tell you which route matches the path and display the name, e.g. api_product_show. Assuming this is the actual route name, then in your template you can probably access it like:

{{ path('api_product_show', { 'id': 3 }) }}

You can also use another command to get a listing of all the routes in your application and then search for the correct one:

bin/console debug:router

It should give you both the name of the route as well as the pattern, but the pattern might not be as easily discernible as when using router:match on the path.

Accessing the API from your controller can be done in multiple ways. Usually you will need an HTTP-client. There is a library called httplug which will give you a common interface over different clients like guzzle, buzz or curl.

With that you just inject the client or get it from the container using:

$client = $this->container->get('httplug.client');

Then you can send a request and read out the response. Keep in mind that you will receive a JSON-payload, not the actual Product-object. You can use the serializer to create the object from the json data, but it is not hooked up to your ORM (Doctrine) and will likely produce weird result if you try to save it.

Since you are in your own application, you might not even want to go through the API in your controller and instead use the Entity directly via Doctrine.

Upvotes: 4

Related Questions