[WIP] Introduce fetch API
| Q | A |
|---|---|
| Type | feature |
| BC Break | no |
| Fixed issues |
Summary
Sometimes you just want to grab something from the interwebz... This PR introduces an API similar to Javascript's fetch and shortcut aliases like the axios package.
It is built on top of the transport system, so that you can quickly transform json or deserialize the result into objects.
By default, it uses the new PsrPreset::sync(), which accepts a raw string as data and returns a PSR-7 Response.
Example usage:
$response = fetch('https://swapi.dev/api/people', [
'headers' => [
'Accept-Language' => 'nl_BE'
],
'transport' => fn(ClientInterface $client) =>
JsonPreset::sync($client, RawUriBuilder::createWithAutodiscoveredPsrFactories())
]);
var_dump($response);
Functions:
- fetch(url[, config])
- get(url[, config])
- delete(url[, config])
- head(url[, config])
- options(url[, config])
- post(url[, data[, config]])
- put(url[, data[, config]])
- patch(url[, data[, config]])
TODO:
- [ ] Tests
- [ ] Better parameter types for optional data / configs / ...
- [ ] Satic analysis improvements
Nice new feature!
Code works pretty well - but psalm is not able to infer the return types. Making it quite hard to use with psalm currently. More info: https://github.com/vimeo/psalm/issues/8487
Alternative is to work with mixed types instead and let upstream deal with figuring out the types - which is not really how I'dd like this to work.
Keeping this one as-is for now!
Nice feature! As a user you could prep a SerializerTransport and just define the output with each call too, eliminating the need to make one for each return type. Though It might break autocompletion.