Skip to main content

HTTP API for Laravel

Two parts of an HTTP API that every service needs and that Laravel leaves to you, built on the standards of the IETF HTTP API working group:

  • Idempotency: a write sent with an Idempotency-Key acts once, however often a client repeats it. A repeat gets the first answer back, and the same key with a different request is refused instead of answered with a result nobody asked for.
  • Problem documents: every failure of an API request is answered as application/problem+json (RFC 9457), with a type, a title and a status a client can rely on.

Installation​

composer require pushery/http-api-for-laravel

The service provider is registered automatically through package discovery. Problem documents work from that moment on for every request under /api. Idempotency starts on the routes you give the middleware.

Configuration​

Publish the configuration file, where every option is documented inline:

php artisan vendor:publish --tag=http-api-config
TagPublishes
http-apieverything below, in one command
http-api-configthe configuration file
http-api-langthe translation files

A setting that reads an environment variable changes without publishing the file:

Environment variableSettingDefault
HTTP_API_ENABLEDhttp-api.enabledtrue
HTTP_API_PROBLEMShttp-api.problems.enabledtrue
HTTP_API_PROBLEM_TYPE_BASEhttp-api.problems.type_basethe problem pages of this portal
HTTP_API_IDEMPOTENCY_STOREhttp-api.idempotency.storethe default cache store
HTTP_API_IDEMPOTENCY_TTLhttp-api.idempotency.ttl86400 seconds
HTTP_API_IDEMPOTENCY_IN_FLIGHT_TTLhttp-api.idempotency.in_flight_ttl600 seconds
HTTP_API_IDEMPOTENCY_MAX_KEY_LENGTHhttp-api.idempotency.max_key_length255 characters

A switch is off for false, 0, no, off and an empty value, written in any case and with spaces around it. Any other value keeps it on. A number that is no number, or one below one, keeps the default.

HTTP_API_ENABLED=false switches the whole package off: the middleware lets every request through as if it were not there, and failures are answered as Laravel answers them.

Translations​

The titles and details of the package's own problems ship in German, English, Spanish, French, Italian, Dutch and Portuguese. A regional locale reads the catalog of its language: pt-BR and pt-PT read pt, en-GB reads en, and so does a region nobody listed, such as fr-CA or de_AT. A catalog you publish for the region under lang/vendor/http-api/pt-BR/ wins over the language key by key.

What it leaves to others​

  • Versioning: a route prefix such as /api/v1 is all an API needs.
  • A request budget with 429 and Retry-After: Laravel's RateLimiter and the throttle middleware. Its 429 is answered as a problem document with the Retry-After header.
  • An OpenAPI document: generated from the routes by a tool such as Scramble.
  • Tokens and signed requests: Sanctum for tokens; a signature between services is the job of the service that sends it.