api-platform / core

The server component of API Platform: hypermedia and GraphQL APIs in minutes
https://api-platform.com
MIT License
2.44k stars 868 forks source link

Example for custom POST #149

Closed Drachenkaetzchen closed 9 years ago

Drachenkaetzchen commented 9 years ago

The documentation doesn't list an example for a custom POST operation. I tried a few things and my custom POST action is being called, however, when I attempt to serialize the newly created entity, I receive "The current request doesn't have an associated resource.". I copied some code from the cpost () method.

My configuration looks like this:

    resource.tempimage.collection_operation.custom_post:
            class:     "Dunglas\ApiBundle\Api\Operation\Operation"
            public:    false
            factory:   [ "@api.operation_factory", "createCollectionOperation" ]
            arguments:
                 -    "@resource.tempimage"               # Resource
                 -    [ "POST" ]                 # Methods
                 -    "/temporaryImage/upload"           # Path
                 -    "PartKeeprImageBundle:TemporaryImage:upload"         # Controller
                 -    "TemporaryImageUpload"                 # Route name
                 -    # Context (will be present in Hydra documentation)
                      "@type":       "hydra:Operation"
                      "hydra:title": "A custom operation"
                      "returns":     "xmls:string"

    resource.tempimage:
        parent:    "api.resource"
        arguments: [ "PartKeepr\\ImageBundle\\Entity\\TempImage" ]
        tags:      [ { name: "api.resource" } ]
        calls:
            -       method:     "initCollectionOperations"
                    arguments: [ [ "@resource.tempimage.collection_operation.custom_post" ] ]

Inside my controller, I try to get the resource, which results in the exception The current request doesn't have an associated resource.:

class TemporaryImageController extends ResourceController {
/**
     * Handles a temporary image upload
     *
     * @Route("/api/temporaryImage/upload", defaults={"method" = "get","_format" = "json"})
     * @RequestParam(name="url",description="An URL where the image is located")
     * ApiDoc(section="image",output="PartKeepr\ImageBundle\Response\TemporaryImageUploadResponse")
     * @View()
     */
    public function uploadAction (Request $request) {
        $resource = $this->getResource($request);
    }
}
*/
dunglas commented 9 years ago

Try to remove the @Route annotation. It is not necessary (and can cause the bug) because the bundle will auto register the route.

Drachenkaetzchen commented 9 years ago

Ouch! Thank you :) Probably this should be mentioned in the documentation and/or checked by the annotation reader?

dunglas commented 9 years ago

A mention in the doc would be cool!

Drachenkaetzchen commented 9 years ago

Closing via #150