结合来自多个API的数据

I have 2 API's, a Company API and a News API. I want to extract News related to a Company so what would be the best practice for achieving this?

Idea 1

  • Client - requests /company/[slug]
  • Company API - returns company data (including company id)
  • Client - requests /news/company/[id]
  • Company API - returns news data for company

In this case the client has to make a request to both API's to get the list of news for a company.

Idea 2

  • Client - requests /company/[slug]/news
  • Company API - works out company id and forwards request onto News API adding in the company id filter
  • News API - returns news data for desired company
  • Company API - passes the response form the new API up to the client.

In this instance only 1 request is made from the client and everything desired is returned in the 1 response

Well if you wanna do that with an database and you were using Doctrine: What would you do?

Exactly! Build an Entity for that issue:

class Company {
    /*
     * @ORM\OneToMany(...)
     */
    private $news;
}

Now if you want to get the company with the id 1 and its news you'd do something like this:

$company = $entityManager->find('Company', 1);
$news    = $company->getNews();

The problem ist that Doctrine can't be used with REST APIs. But there's a driver for Doctrine that is working with REST APIs. This should do the trick:

https://github.com/CircleOfNice/DoctrineRestDriver

/*
 * @DataSource\Select("http://yourapi.com/company/{id}")
 */
class Company {}

/*
 * @DataSource\Select("http://yourapi2.com/news/{id}")
 */
class News {}