|
| 1 | +# Reading package metadata via API |
| 2 | + |
| 3 | +To read the package metadata via API, use the Composer API on your Private Packagist repository. |
| 4 | + |
| 5 | +This is useful when you need to programmatically access package metadata beyond what's available through the Private Packagist API |
| 6 | +(for example to read custom configuration from the `extra` section of a package's composer.json). |
| 7 | + |
| 8 | +Read more about the API: https://packagist.org/apidoc#get-package-data |
| 9 | + |
| 10 | + |
| 11 | +### Example implementation |
| 12 | + |
| 13 | +The process works as follows: |
| 14 | +1. Get the JSON from `https://repo.packagist.com/<org>/p2/<package>.json` |
| 15 | +2. Authenticate using username `token` and an Authentication Token as password |
| 16 | +3. Decode the JSON as nested arrays |
| 17 | +4. Use [MetadataMinifier](https://github.com/composer/metadata-minifier) to expand the metadata for each package version: `$metadata = MetadataMinifier::expand($data['packages'][$package])` |
| 18 | + |
| 19 | +```bash |
| 20 | +# Make sure the composer/metadata-minifer package is installed: |
| 21 | +composer require composer/metadata-minifier |
| 22 | +``` |
| 23 | + |
| 24 | +```php |
| 25 | +use Composer\MetadataMinifier\MetadataMinifier; |
| 26 | + |
| 27 | +// Assuming your organization name is acme-company and the package name is acme/package |
| 28 | +$organization = 'acme-company'; |
| 29 | +$package = 'acme/package'; |
| 30 | + |
| 31 | +// NOTE: You must use an authentication token for the composer API, not the Private Packagist API credentials. |
| 32 | +// You can create a token in your Organization settings > Authentication Tokens |
| 33 | +$token = 'packagist_ort_..........'; |
| 34 | + |
| 35 | +// The p2/$vendor/$package.json endpoint contains only tagged releases. If you want to fetch information about branches (i.e. dev versions) |
| 36 | +// you need to use p2/$vendor/$package~dev.json. |
| 37 | +$apiUrl = sprintf('https://repo.packagist.com/%s/p2/%s.json', $organization, $package); |
| 38 | + |
| 39 | +$ch = curl_init($apiUrl); |
| 40 | +curl_setopt_array($ch, [ |
| 41 | + CURLOPT_RETURNTRANSFER => true, |
| 42 | + CURLOPT_HTTPAUTH => CURLAUTH_BASIC, |
| 43 | + CURLOPT_USERPWD => 'token:' . $token |
| 44 | +]); |
| 45 | + |
| 46 | +$response = curl_exec($ch); |
| 47 | +curl_close($ch); |
| 48 | + |
| 49 | +$data = json_decode($response, true); |
| 50 | +$metadata = MetadataMinifier::expand($data['packages'][$package]); |
| 51 | +``` |
| 52 | + |
| 53 | + |
0 commit comments