从Drupal 9通过外部API检索数据

huangapple go评论54阅读模式
英文:

Retrieve data via an external API on Drupal 9

问题

我正在使用Drupal 9,并且想从外部API获取一些数据,我搜索了一些解决方案。一个解决方案是使用guzzlehttp库,所有网站都说要使用一些代码进行guzzlehttp请求,但没有一个说清楚代码应该添加在哪里!请帮助我,我不知道该怎么办?如果有更好的解决方案,请指导我。谢谢...

英文:

I'm using drupal 9 and I want get some data from external API, I searched for solutions. One solution is using guzzlehttp library, and all the sites say make guzzlehttp request with some codes, but none of them said where the code should be added! please help me, I don't know what to do? If there are better solutions, please guide me.
Thanks...

答案1

得分: 0

你可以创建一个自定义模块或使用现有的模块来添加你的代码,如果你想在控制器中获取数据,那么将这段代码添加到你的控制器函数中,否则你可以将其添加到你的.module文件中进行测试。以下是在Drupal 9、10中从外部API检索数据的示例:

function FUNCTION_NAME() {
  $url = 'https://api.example.com/data';
  $response = \Drupal::httpClient()->get($url);
  $data = json_decode($response->getBody(), TRUE);
  return $data;
}
英文:

You can create a custom module or use an existing one to add your code, if you want to fetch data in controller then add this code in you controller function or else you can add in your .module file for testing. Here is an example to retrieve data from an external API in Drupal 9, 10

function FUNCTION_NAME() {
  $url = 'https://api.example.com/data';
  $response = \Drupal::httpClient()->get($url);
  $data = json_decode($response->getBody(), TRUE);
  return $data;
}

答案2

得分: 0

Guzzle已经被添加到composer中,默认运行。

现在,您想要如何调用另一个REST API?

通过控制器、RESTful API或服务,以便上述功能正常工作,否则提供更多预期功能。

英文:

Guzzle already added inside composer, runs by default.

Now, how you want to call another rest-api?

Through controller, Restful API or service, so above function works, or else give more expected functionality.

huangapple
  • 本文由 发表于 2023年5月6日 18:03:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/76188293.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定