---
title: "HTTP Project"
description: "Derafu HTTP"
type: "docs"
category: "doc"
tags: [php]
authors: [Anonymous]
date: "2026-08-21"
last_update: "2026-08-21"
time_minutes: 1
draft: false
unlisted: false
url: "https://www.derafu.dev/docs/core/http"
---

# Derafu HTTP



---

## Introduction

Standard-Compliant HTTP Library with Extended Features

# Standard-Compliant HTTP Library with Extended Features

![GitHub last commit](https://img.shields.io/github/last-commit/derafu/http/main)
![CI Workflow](https://github.com/derafu/http/actions/workflows/ci.yml/badge.svg?branch=main&amp;event=push)
![GitHub code size in bytes](https://img.shields.io/github/languages/code-size/derafu/http)
![GitHub Issues](https://img.shields.io/github/issues-raw/derafu/http)
![Total Downloads](https://poser.pugx.org/derafu/http/downloads)
![Monthly Downloads](https://poser.pugx.org/derafu/http/d/monthly)

A PSR and RFC compliant HTTP library that provides elegant request/response handling, content negotiation and problem details for PHP applications.

## Why Derafu\Http?

### 🎯 **Simple, but not limited, HTTP Handling**

Most HTTP libraries either do too much or too little. Derafu\Http provides:

- **Extended Request/Response**: Smart content type negotiation and safe data access.
- **Content Negotiation**: Intelligent format detection and response transformation.
- **Problem Details**: RFC 7807 implementation for structured error handling.
- **PSR Compliance**: Built on PSR-7 and PSR-15 standards.
- **Middleware Architecture**: Flexible request/response processing pipeline.

### ✨ **Key Features**

- **Smart Request Handling**: Safe access to query, post, and JSON data.
- **Intelligent Responses**: Automatic content negotiation and format transformation.
- **Structured Errors**: Complete RFC 7807 Problem Details implementation.
- **Modular Design**: Core HTTP functionality with middleware support.
- **Type Safety**: Use of enums for HTTP status codes and content types.
- **Middleware Pipeline**: PSR-15 compliant middleware chain for request processing.

## Installation

```bash
composer require derafu/http
```

## Basic Usage

### public/index.php

```php
use Derafu\Http\Kernel;
use Derafu\Kernel\Environment;

require_once dirname(__DIR__) . &#039;/app/bootstrap.php&#039;;

return fn (array $context): Kernel =&gt; new Kernel(new Environment(
    $context[&#039;APP_ENV&#039;],
    (bool) $context[&#039;APP_DEBUG&#039;],
    $context
));
```

### Middleware Configuration

The library uses PSR-15 middlewares for request processing. Configure your middleware stack in the services file, for example `services.yaml`:

```yaml
# Core middlewares in required order.
Psr\Http\Server\RequestHandlerInterface:
    class: Derafu\Http\Service\RequestHandler
    public: true
    arguments:
        $middlewares:
            - &#039;@Derafu\Http\Middleware\RequestFactoryMiddleware&#039;
            - &#039;@Derafu\Http\Middleware\RouterMiddleware&#039;
            - &#039;@Derafu\Http\Middleware\DispatcherMiddleware&#039;
            - &#039;@Derafu\Http\Middleware\ResponseNormalizerMiddleware&#039;

# Register individual middlewares.
Derafu\Http\Middleware\RequestFactoryMiddleware: ~
Derafu\Http\Middleware\RouterMiddleware: ~
Derafu\Http\Middleware\DispatcherMiddleware: ~
Derafu\Http\Middleware\ResponseNormalizerMiddleware: ~
```

### Core Middlewares

The library includes four essential middlewares that must be configured in order:

1. **RequestFactoryMiddleware**: Converts PSR-7 requests to Derafu requests.
2. **RouterMiddleware**: Handles URL routing and route matching.
3. **DispatcherMiddleware**: Executes route handlers (controllers, closures or templates).
4. **ResponseNormalizerMiddleware**: Ensures PSR-7 compliant responses.

### Custom Middlewares

Create custom middlewares by implementing PSR-15&#039;s `MiddlewareInterface`:

```php
class CustomMiddleware implements MiddlewareInterface
{
    public function process(
        ServerRequestInterface $request,
        RequestHandlerInterface $handler
    ): ResponseInterface {
        // Process request.
        $response = $handler-&gt;handle($request);
        // Process response.
        return $response;
    }
}
```

### Working with Requests

```php
// Safe access to request data.
$id = $request-&gt;query(&#039;id&#039;, 0);
$data = $request-&gt;json();
$file = $request-&gt;file(&#039;document&#039;);

// Content negotiation.
$format = $request-&gt;getPreferredFormat();
```

### Creating Responses

```php
// Automatic content negotiation.
// Returns JSON for API requests in `/api` paths
return [&#039;status&#039; =&gt; &#039;ok&#039;];

// Explicit responses.
return (new Response())-&gt;asJson($data)-&gt;withHttpStatus(HttpStatus::CREATED);

// Redirect.
return (new Response())-&gt;redirect(&#039;https://www.example.com&#039;);
```

### Error Handling with Problem Details

Any exception will be treated as &quot;Problem Detail&quot; (RFC 7807). To have control over all fields, exceptions must implement `HttpExceptionInterface`.

```json
{
    &quot;type&quot;: &quot;about:blank&quot;,
    &quot;title&quot;: &quot;Not Found&quot;,
    &quot;status&quot;: 404,
    &quot;detail&quot;: &quot;No route found for \&quot;/api/mustFail\&quot;.&quot;,
    &quot;instance&quot;: &quot;/api/mustFail&quot;,
    &quot;extensions&quot;: {
        &quot;timestamp&quot;: &quot;2025-02-20T22:04:25+00:00&quot;,
        &quot;environment&quot;: &quot;dev&quot;,
        &quot;debug&quot;: true,
        &quot;context&quot;: [],
        &quot;throwable&quot;: null
    }
}
```

## Integration with Other Packages

Derafu\Http is designed to work with other Derafu packages:

### Required

- **derafu/kernel**: The core of the application, with dependency injection.
- **derafu/renderer**: For template rendering, with dependency on **derafu/twig**.
- **derafu/routing**: For URL routing, with autodiscovery of templates.
- **derafu/translation**: For I18n, with a simple translator that supports ICU.

### Optional

- **derafu/markdown**: For renderig templates in markdown format.

### Suggested

- **derafu/data-processor**: For data processing: format, cast, sanitize and validate.




---

## HTTP Flow

Flow - Detailed Explanation

# Flow - Detailed Explanation

The Derafu HTTP component implements a clean, modular approach to handling HTTP requests in PHP applications. The flow diagram illustrates how an HTTP request travels through the system, from the initial client request to the final response delivery.

{.w-75 .mx-auto}
![HTTP Flow](https://www.derafu.dev/img/diagrams/content/docs/core/http/derafu-http-flow.svg)

## Key Components

### Client

The external entity (browser, API consumer, etc.) that initiates the HTTP request and receives the response.

### Runtime
The application&#039;s entry point and execution environment. It serves as the orchestrator of the entire HTTP flow, responsible for:

- Bootstrapping the application.
- Creating the PSR-7 request object from the HTTP request.
- Initializing the kernel.
- Delegating request processing.
- Sending the response back to the client.

### Kernel

The core of the application, responsible for:

- Building and configuring the dependency injection container.
- Loading application configurations.
- Managing the application lifecycle.
- Coordinating the request handling process.

The Kernel implements a micro-kernel architecture that keeps the core small and efficient while pushing most functionality to handlers and middleware.

### Request Handler

Processes the HTTP request and produces a response. Handlers:

- Receive the request from the kernel.
- Apply application logic.
- Generate an appropriate response.
- May use services from the container to fulfill the request.

### Request

A PSR-7 compliant ServerRequest object that represents the HTTP request. It encapsulates:

- HTTP method.
- URI and query parameters.
- Headers.
- Body content.
- Server and environment variables.

### Response

A PSR-7 compliant Response object that represents the HTTP response. It includes:

- Status code.
- Headers.
- Response body.

### Container

The dependency injection container that:

- Manages service instantiation and configuration.
- Provides service dependencies throughout the application.
- Implements the PSR-11 container interface.
- Supports autowiring for simplified service definition.

## The HTTP Request/Response Flow

1. **Client Sends HTTP Request**
   The flow begins when a client makes an HTTP request to the application.

2. **Runtime Creates Request Object**
   The Runtime transforms the raw HTTP request into a PSR-7 compliant Request object, preparing it for processing.

3. **Runtime Initializes Kernel**
   The Kernel is initialized with the necessary configurations to process the current request.

4. **Kernel Builds Container**
   The Kernel builds and configures the dependency injection container, making all application services available.

5. **Runtime Delegates Request Processing**
   The Runtime passes the Request object to the Kernel for processing.

6. **Kernel Delegates to Handler**
   The Kernel identifies the appropriate Request Handler based on routing information and delegates the request processing.

7. **Handler Generates Response**
   The Handler applies business logic, interacts with the application services as needed, and generates a Response object.

8. **Response Returned to Runtime**
   The generated Response is returned through the call chain back to the Runtime.

9. **Runtime Sends Response to Client**
   The Runtime outputs the Response to the client, completing the HTTP cycle.




---

## Design Principles

Design Principles

# Design Principles

The Derafu HTTP component provides a lightweight, standards-compliant approach to HTTP request handling. By following established PHP interoperability standards (PSRs) and sound architectural principles, it enables the development of robust, maintainable web applications with minimal overhead.

The Derafu HTTP is designed with several key principles in mind:

## PSR Compliance

- Implements PSR-7 for HTTP messages.
- Follows PSR-11 for container interoperability.
- Supports PSR-15 for middleware.

## Separation of Concerns

Each component has a single, well-defined responsibility:

- Runtime manages the application lifecycle.
- Kernel coordinates processing.
- Handlers implement business logic.
- Container manages dependencies.

## Flexibility

The design allows for:

- Custom request handlers.
- Middleware integration.
- Extensible container configuration.
- Multiple runtime environments.

## Testability

The clear separation of components and dependency injection make unit testing straightforward:

- Mock the container for handler tests.
- Create test requests easily.
- Validate responses without invoking the full stack.

## Implementation Guidelines

When working with the Derafu HTTP component:

1. **Define Request Handlers** for different routes or endpoints.
2. **Configure the Container** with your application services.
3. **Set up your routes** to map URLs to handlers.
4. **Extend the base classes** as needed for custom functionality.

The architecture is designed to be minimal yet powerful, allowing developers to focus on the business logic rather than HTTP processing details.





---
Last updated on 21/08/2026
#php
