简体   繁体   中英

Symfony 4 REST API Request validation. (POST DATA)

I am continuing to learn symfony and this time i would like to receive any ideas about how to correctly validate request post data before we store it. I am trying to have as small controller as it's possible. I've read about DTO. (To implement validation using it). Also i see that we can validate request using entity comments. Example:

use Symfony\Component\Validator\Constraints as Assert;
class Author
{
    /**
     * @Assert\NotBlank
     */
    private $name;
}

Please, give me some examples how do you validate incoming request data in symfony rest api. As a Laravel developer i can say we can do it this way:

public function store(Request $request)
{
    $validated = $request->validate([
        'title' => 'required|unique:posts|max:255',
        'body' => 'required',
    ]);

    // The blog post is valid...
}

Or we can use TypeHinting:

    public function store(StorePostRequest $request)
    {
        // The incoming request is valid...
    
        // Retrieve the validated input data...
        $validated = $request->validated();
}

How can we do it in symfony saving the idea of thin controller?

You can use Assert annotations in your entity en use ValidatorInterface in your controller

public function store(Request $request, ValidatorInterface $validator): json {
    $author = new Author();
    $author->setName($request->get('name'));
    // ... Hydrate $author properties ...

    $errors = $validator->validate($author);
    if (count($errors) > 0) {
        $errorsString = (string) $errors;
        return $this->json(['status' => 'error', 'message' => (string) $errorsString]);
    }

    return $this->json(['status' => 'success', 'author' => $author);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM