PHPackages                             tiny-blocks/http - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [HTTP &amp; Networking](/categories/http)
4. /
5. tiny-blocks/http

ActiveLibrary[HTTP &amp; Networking](/categories/http)

tiny-blocks/http
================

Common implementations for HTTP protocol.

4.8.0(2mo ago)322.8k↓33.3%1MITPHPPHP ^8.5CI passing

Since Aug 6Pushed 2mo agoCompare

[ Source](https://github.com/tiny-blocks/http)[ Packagist](https://packagist.org/packages/tiny-blocks/http)[ Docs](https://github.com/tiny-blocks/http)[ RSS](/packages/tiny-blocks-http/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (9)Versions (30)Used By (1)

Http
====

[](#http)

[![License](https://camo.githubusercontent.com/f8df3091bbe1149f398a5369b2c39e896766f9f6efba3477c63e9b4aa940ef14/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d677265656e)](LICENSE)

- [Overview](#overview)
- [Installation](#installation)
- [How to use](#how-to-use)
    - [Request](#request)
    - [Response](#response)
- [License](#license)
- [Contributing](#contributing)

Overview
--------

[](#overview)

Common implementations for the HTTP protocol. The library exposes concrete implementations that follow the PSR standards and are **framework-agnostic**, designed to work consistently across any ecosystem that supports [PSR-7](https://www.php-fig.org/psr/psr-7) and [PSR-15](https://www.php-fig.org/psr/psr-15), providing solutions for building HTTP responses, requests, and other HTTP-related components.

Installation
------------

[](#installation)

```
composer require tiny-blocks/http
```

How to use
----------

[](#how-to-use)

The library exposes interfaces like `Headers` and concrete implementations like `Request`, `Response`, `ContentType`, and others, which facilitate construction.

### Request

[](#request)

#### Decoding a request

[](#decoding-a-request)

The library provides a small public API to decode a PSR-7 `ServerRequestInterface` into a typed structure, allowing you to access route parameters and JSON body fields consistently.

- **Decode a request**: Use `Request::from(...)` to wrap the PSR-7 request and call `decode()`. The decoded object exposes `uri` and `body`.

    ```
    use Psr\Http\Message\ServerRequestInterface;
    use TinyBlocks\Http\Request;

    /** @var ServerRequestInterface $psrRequest */
    $decoded = Request::from(request: $psrRequest)->decode();

    $name = $decoded->body()->get(key: 'name')->toString();
    $payload = $decoded->body()->toArray();

    $id = $decoded->uri()->route()->get(key: 'id')->toInteger();
    ```
- **Access the HTTP method**: Use `method()` directly on the `Request` to retrieve the HTTP verb as a typed `Method`enum.

    ```
    use Psr\Http\Message\ServerRequestInterface;
    use TinyBlocks\Http\Request;

    /** @var ServerRequestInterface $psrRequest */
    $request = Request::from(request: $psrRequest);

    $method = $request->method();        # Method::POST
    $method->value;                      # "POST"
    ```
- **Access the full URI**: Use `toString()` on the decoded `uri()` to retrieve the complete request URI as a string.

    ```
    use TinyBlocks\Http\Request;

    $decoded = Request::from(request: $psrRequest)->decode();

    $fullUri = $decoded->uri()->toString(); # "https://api.example.com/v1/dragons?sort=name"
    ```
- **Access query parameters**: Use `queryParameters()` on the decoded `uri()` to retrieve typed access to query string values. Each value is returned as an `Attribute`, providing the same safe conversions and defaults as body fields.

    ```
    use TinyBlocks\Http\Request;

    $decoded = Request::from(request: $psrRequest)->decode();

    $queryParams = $decoded->uri()->queryParameters()->toArray();                     # ['sort' => 'name', 'limit' => '50']
    $sort = $decoded->uri()->queryParameters()->get(key: 'sort')->toString();         # "name"
    $limit = $decoded->uri()->queryParameters()->get(key: 'limit')->toInteger();      # 50
    $active = $decoded->uri()->queryParameters()->get(key: 'active')->toBoolean();    # default: false
    ```
- **Typed access with defaults**: Each value is returned as an Attribute, which provides safe conversions and default values when the underlying value is missing or not compatible.

    ```
    use TinyBlocks\Http\Request;

    $request = Request::from(request: $psrRequest);
    $decoded = $request->decode();

    $method = $request->method();                                                  # default: Method enum

    $id = $decoded->uri()->route()->get(key: 'id')->toInteger();                   # default: 0
    $uri = $decoded->uri()->toString();                                            # default: ""
    $sort = $decoded->uri()->queryParameters()->get(key: 'sort')->toString();      # default: ""
    $limit = $decoded->uri()->queryParameters()->get(key: 'limit')->toInteger();   # default: 0

    $note = $decoded->body()->get(key: 'note')->toString();                        # default: ""
    $tags = $decoded->body()->get(key: 'tags')->toArray();                         # default: []
    $price = $decoded->body()->get(key: 'price')->toFloat();                       # default: 0.00
    $active = $decoded->body()->get(key: 'active')->toBoolean();                   # default: false
    ```
- **Custom route attribute name**: If your framework stores route params in a different request attribute, you can specify it via `route()`.

    ```
    use TinyBlocks\Http\Request;

    $decoded = Request::from(request: $psrRequest)->decode();

    $id = $decoded->uri()->route(name: '_route_params')->get(key: 'id')->toInteger();
    ```

#### How route parameters are resolved

[](#how-route-parameters-are-resolved)

The library resolves route parameters from the PSR-7 `ServerRequestInterface` using a **multistep fallback strategy**, designed to work across different frameworks without importing any framework-specific code.

**Resolution order** (when using the default `route()` or `route(name: '...')`):

1. **Specified attribute lookup** — Reads the attribute from the request using the configured name (default: `__route__`).

    - If the value is an **array**, the key is looked up directly.
    - If the value is an **object**, the resolver tries known accessor methods (`getArguments()`, `getMatchedParams()`, `getParameters()`, `getParams()`) and then public properties (`arguments`, `params`, `vars`, `parameters`).
    - If the value is a **scalar** (e.g., a string), it is returned as-is.
2. **Known attribute scan** (only when using the default `__route__` name) — Scans all commonly used attribute keys across frameworks:

    - `__route__`, `_route_params`, `route`, `routing`, `routeResult`, `routeInfo`
3. **Direct attribute fallback** — As a last resort, tries `$request->getAttribute($key)` directly, which supports frameworks like Laravel that store route params as individual request attributes.
4. **Safe default** — If nothing is found, returns `Attribute::from(null)`, which provides safe conversions: `toInteger()` → `0`, `toString()` → `""`, `toFloat()` → `0.00`, `toBoolean()` → `false`, `toArray()` → `[]`.

**Supported frameworks and attribute formats:**

FrameworkAttribute KeyFormat**Slim 4**`__route__`Object with `getArguments()`**Mezzio / Expressive**`routeResult`Object with `getMatchedParams()`**Symfony**`_route_params``array`**Laravel***(direct)*`getAttribute('id')` directly on the request**FastRoute (generic)**`routeInfo`Array with route parameters**Manual injection**Any custom key`$request->withAttribute('__route__', [...])`#### Manually injecting route parameters

[](#manually-injecting-route-parameters)

If your framework or middleware does not automatically populate route attributes, you can inject them manually using PSR-7's `withAttribute()`:

```
use TinyBlocks\Http\Request;

$psrRequest = $psrRequest->withAttribute('__route__', [
    'id'    => '42',
    'email' => 'user@example.com'
]);

$decoded = Request::from(request: $psrRequest)->decode();
$id = $decoded->uri()->route()->get(key: 'id')->toInteger(); # 42

$psrRequest = $psrRequest->withAttribute('my_params', ['slug' => 'hello-world']);
$slug = Request::from(request: $psrRequest)
    ->decode()
    ->uri()
    ->route(name: 'my_params')
    ->get(key: 'slug')
    ->toString(); # "hello-world"
```

### Response

[](#response)

#### Creating a response

[](#creating-a-response)

The library provides an easy and flexible way to create HTTP responses, allowing you to specify the status code, headers, and body. You can use the `Response` class to generate responses, and the result will always be a `ResponseInterface` from the PSR, ensuring compatibility with any framework that adheres to the [PSR-7](https://www.php-fig.org/psr/psr-7) standard.

- **Creating a response with a body**: To create an HTTP response, you can pass any type of data as the body. Optionally, you can also specify one or more headers. If no headers are provided, the response will default to `application/json` content type.

    ```
    use TinyBlocks\Http\Response;

    Response::ok(body: ['message' => 'Resource created successfully.']);
    ```
- **Creating a response with a body and custom headers**: You can also add custom headers to the response. For instance, if you want to specify a custom content type or any other header, you can pass the headers as additional arguments.

    ```
    use TinyBlocks\Http\Response;
    use TinyBlocks\Http\ContentType;
    use TinyBlocks\Http\CacheControl;
    use TinyBlocks\Http\ResponseCacheDirectives;

    $body = 'This is a plain text response';

    $contentType = ContentType::textPlain();

    $cacheControl = CacheControl::fromResponseDirectives(
        maxAge: ResponseCacheDirectives::maxAge(maxAgeInWholeSeconds: 10000),
        staleIfError: ResponseCacheDirectives::staleIfError()
    );

    Response::ok($body, $contentType, $cacheControl)
        ->withHeader(name: 'X-ID', value: 100)
        ->withHeader(name: 'X-NAME', value: 'Xpto');
    ```

#### Using the status code

[](#using-the-status-code)

The library exposes a concrete implementation through the `Code` enum. You can retrieve the status codes, their corresponding messages, and check for various status code ranges using the methods provided.

- **Get message**: Returns the [HTTP status message](https://developer.mozilla.org/en-US/docs/Web/HTTP/Messages)associated with the enum's code.

    ```
    use TinyBlocks\Http\Code;

    Code::OK->value;                        # 200
    Code::OK->message();                    # OK
    Code::IM_A_TEAPOT->message();           # I'm a teapot
    Code::INTERNAL_SERVER_ERROR->message(); # Internal Server Error
    ```
- **Check if the code is valid**: Determines if the given code is a valid HTTP status code represented by the enum.

    ```
    use TinyBlocks\Http\Code;

    Code::isValidCode(code: 200); # true
    Code::isValidCode(code: 999); # false
    ```
- **Check if the code is an error**: Determines if the given code is in the error range (**4xx** or **5xx**).

    ```
    use TinyBlocks\Http\Code;

    Code::isErrorCode(code: 500); # true
    Code::isErrorCode(code: 200); # false
    ```
- **Check if the code is a success**: Determines if the given code is in the success range (**2xx**).

    ```
    use TinyBlocks\Http\Code;

    Code::isSuccessCode(code: 500); # false
    Code::isSuccessCode(code: 200); # true
    ```

License
-------

[](#license)

Http is licensed under [MIT](LICENSE).

Contributing
------------

[](#contributing)

Please follow the [contributing guidelines](https://github.com/tiny-blocks/tiny-blocks/blob/main/CONTRIBUTING.md) to contribute to the project.

###  Health Score

54

—

FairBetter than 97% of packages

Maintenance84

Actively maintained with recent releases

Popularity29

Limited adoption so far

Community12

Small or concentrated contributor base

Maturity75

Established project with proven stability

 Bus Factor1

Top contributor holds 96.8% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~48 days

Recently: every ~3 days

Total

28

Last Release

83d ago

Major Versions

1.1.0 → 2.0.02023-06-08

2.1.6 → 3.0.02024-02-04

3.2.0 → 4.0.02024-12-19

PHP version history (5 changes)1.0.0PHP ^8.1

2.0.0PHP ^8.1||^8.2

3.0.0PHP ^8.2

4.0.0PHP ^8.3

4.2.0PHP ^8.5

### Community

Maintainers

![](https://www.gravatar.com/avatar/b00a83241d2af272255f1755bf6aff48e77821c59ef623520176d9e828977241?d=identicon)[gustavofreze](/maintainers/gustavofreze)

---

Top Contributors

[![gustavofreze](https://avatars.githubusercontent.com/u/22873481?v=4)](https://github.com/gustavofreze "gustavofreze (60 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (2 commits)")

---

Tags

hacktoberfesthttp-codeshttp-methodsopen-sourcephpprotocolpsr-15psr-7requestresponsestatus-codehttpresponserequestpsrpsr-7psr-15http statustiny-blockshttp codehttp-methods

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP\_CodeSniffer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/tiny-blocks-http/health.svg)

```
[![Health](https://phpackages.com/badges/tiny-blocks-http/health.svg)](https://phpackages.com/packages/tiny-blocks-http)
```

###  Alternatives

[psr/http-factory

PSR-17: Common interfaces for PSR-7 HTTP message factories

1.9k692.9M1.9k](/packages/psr-http-factory)[psr/http-server-handler

Common interface for HTTP server-side request handler

177101.3M921](/packages/psr-http-server-handler)[psr/http-server-middleware

Common interface for HTTP server-side middleware

18291.2M1.5k](/packages/psr-http-server-middleware)[idealo/php-middleware-stack

Implementation of HTTP Middleware PSR-15 specification

318.9k](/packages/idealo-php-middleware-stack)[art4/requests-psr18-adapter

Use WordPress/Requests as a PSR-18 HTTP client

153.3k](/packages/art4-requests-psr18-adapter)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
