I have an event page for viewing movies showtime and i want to connect to a 3rd party api to get the movie's info ( show time, cinema name,...etc ) how to do it? can i do this without having to create a plugin to control the request ? any ideas would help me get a clear understanding of this concept/code would be very appreciated.
1 Answer
Unless there's a community plugin specifically built for connecting to this API, you're gonna have to build your own. But a simple module to connect to a third-party API and get some basic data is not super difficult.
Here's all the code you need for a basic API request:
$guzzle = \Craft::createGuzzleClient();
// replace with the URL & endpoint you want to look up
$requestUrl = 'https://your-api-domain.com/movies/123';
$response = $guzzle->request(
'GET',
$requestUrl,
);
$success = $response->getStatusCode() === 200;
$data = $response->getBody();
If the API requires authentication or specific headers, you can add those as the third argument to the request()
method. See the documentation for Guzzle for details.
Now you only need to figure out two things:
- WHEN do you query the API for WHAT information? On the press of a button, when a specific action is taken in the backend, whenever a specific page is visited? You can use event hooks to trigger your API requests at specific points in your workflow (for example, whenever an entry for an event is saved, so you can add additional information from the API).
- WHERE do you store the API response? If you want to save the response to your entries, look at documentation on how to update entries programmatically. If you want to display the response data directly, you may not need to save it at all (though I would make sure to cache it to avoid hitting the API too many times).
-
1