OpenAPITools / OpenAPITools/openapi-generator

[REQ][Slim4] Request Validation

Open
#3,733 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Enhancement: Feature Server: PHP
Dominant language
Java
Stars
26.8k
Forks
7.7k
PR merge metrics
PR metrics pending

Description

Is your feature request related to a problem? Please describe.

I thought about perfect API implementation a lot and I think it should contain 5 steps mock -> auth -> validation -> business logic -> process and exactly in that order.

  1. Mock step returns example response when mock feature is enabled. Skipped otherwise. Feature discussion #3545
  2. Auth(authentication) step checks authorization. Returns 401 Unauthorized when token/credentials are invalid.
  3. Validation step should validate all request parameters. Just basic validation, data types comparison, etc. Returns 400 Bad Request on fail.
  4. Business Logic step is part of validation but checks if request cannot be processed by other reasons(username already exists, premium account required, etc.). Returns 400 Bad Request with verbose error description on fail.
  5. Process step executes request and returns final response with 2xx http status code. Most of time this step related to database/storage quering.

Current issue related to third step Validation.

Describe the solution you'd like

PHP Slim4 server should contain validation middleware. Something like that:

use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface as RequestHandler;
use Slim\Psr7\Response;

class ValidationMiddleware implements MiddlewareInterface
{
    public function process(Request $request, RequestHandler $handler): Response
    {
        if ($this->validate($request) === true) {
            // everything fine, continue
            return $handler->handle($request);
        }

        // request is malformed or invalid, return client error response
        $response = new Response();
        // just an example of client error response body
        $response->getBody()->write(json_encode([
            'error' => 'invalid request',
            'error_description' => 'Request is malformed or invalid.',
        ]));
        // common practice to return 4xx status response when client request cannot be prcocessed
        // most of time you'll see '400 Bad Request' or '422 Unprocessable Entity'
        return $response->withStatus(400);
    }

    public function validate(Request $request): bool
    {
        // let's imagine that accordingly to spec current request
        // must contain 'username' query param as string less or equal 50 chars
        $params = $request->getQueryParams();
        if (is_string($params['username']) && mb_strlen($params['username']) <= 50) {
            return true;
        }

        return false;
    }
}

Additional context

I'm working on that feature. This issue created to describe how Slim4 server will be enhanced, kind of roadmap.

cc @jebentier, @dkarlovi, @mandrean, @jfastnacht, @ackintosh, @renepardon

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

The issue names no repository files, tests, or generator entry points. Start by locating the PHP Slim4 server generator and its middleware structure, then determine how request parameters should be validated, how invalid requests return 400 responses, and how valid requests continue to the handler.

Written by the indexing model from the issue text.

Assessment

Tech stack
php
Domain
api, backend
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.