Search code examples
restsymfonyfosrestbundle

multipart/form-data and FormType validation


I am building an API using the FOSRestBundle and am at the stage where I need to implement the handling of the creation of new entities that contain binary data.

Following the methods outlined on Sending binary data along with a REST API request sending the data as multipart/form-data feels the most practical for our implementation due to the ~33% added bandwidth required for Base64.

Question

How can I configure the REST end point to both handle the file within the request and perform validation on the JSON encoded entity when sending the data as multipart/form-data?

When just sending the raw JSON I have been using Symfony's form handleRequest method to perform validation against the custom FormType. For example:

$form = $this->createForm(new CommentType(), $comment, ['method' => 'POST']);
$form->handleRequest($request);

if ($form->isValid()) {

  // Is valid

}

The reason I like this approach is so that I can have more control over the population of the entity depending whether the action is an update (PUT) or new (POST).

I understand that Symfony's Request object handles the request such that previously the JSON data would be the content variable but is now keyed under request->parameters->[form key] and the files within the file bag (request->files).


Solution

  • After giving up and looking at an alternative option of having a separate endpoint for the image upload. For example:

    1. Create the new comment.

    POST /comments

    1. Upload image to end point

    POST /comments/{id}/image

    I found there is already a bundle which provides various RESTful uploading processes. One of which was the one I originally wanted of being able to parse multipart/form-data into an entity whilst extracting the file.