Hello,
you can get the data from the api via file_get_contents this gets you a string, you can then json_decode it to use it as an array if needed:
$api = file_get_contents('https://api.sampleapis.com/beers/ale');
$array = json_decode($api);
Hi @kamalkayani.
Another way to do this is to use the internal WordPress HTTP API, to make requests to external APIs in PHP:
https://developer.ww.wp.xz.cn/plugins/http-api/
For storing the API, please could you explain what you mean by “the block will not have access to the options”.
Thanks @benniledl and @psykro.
@psykra I mean the WordPress options available to the normal plugins.
In a normal plugin, I can let the user enter their API key by providing a form field in the plugin settings but for a block plugin for block directory how can I get a user defined API key.
Your block plugins should contain a block, and a minimum of other supporting code. It should not contain any UX outside of the editor, such as WordPress options or wp-admin menus. Server-side code should be kept to a minimum.
source: https://github.com/WordPress/wporg-plugin-guidelines/blob/block-guidelines/blocks.md
@kamalkayani Indeed. As it states further down in those guidelines…
First up, some clarity. For the purposes of the Block Directory, we distinguish between two types of plugins:
- Plugins that exist solely to distribute a block.
- All other plugins, including those that bundle many independent blocks, plugins that contain blocks in addition to other functionality, and plugins with no blocks at all.
These guidelines apply specifically to the first type of plugin, which we’ll call here a Block Plugin. If your plugin is of the second type, then the further guidelines and restrictions do not apply to your work. All plugins, be they block-only or not, are required to comply with the Detailed Plugin Guidelines https://developer.ww.wp.xz.cn/plugins/wordpress-org/detailed-plugin-guidelines/.
In my opinion, because you need to store an API key for your block to work, that additional functionality pushes it outside of the constraints of a “Block Plugin” ie a plugin that exist solely to distribute a block, and into regular plugin territory.
Got it. Thanks for the clarification.