2

I use Symfony Flex and Composer with the Symfony 4 and installed API Platform's server component in my app.

How to add an endpoint in Swagger (OpenAPI) for custom controller?

<?php
/**
 * Application features
 */

namespace App\Controller;

use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Annotation\Route;

/**
 * Checks if the service is alive.
 *
 * @package Behat\Behat\Context\Context
 */
class HealthcheckController
{
    /**
     * @Route(
     *     name="api_healthcheck_entrypoint",
     *     path="/api/ping",
     *     methods={"GET"},
     * )
     */
    public function __invoke()
    {
        return new JsonResponse(array('ping' => 'pong'));
    }
}

docker-compose exec php bin/console api:swagger:export

    {
        "swagger": "2.0",
        "basePath": "\/",
        "info": {
            "title": "FastTony.es",
            "version": "0.0.1"
        },
        "paths": {},
        "securityDefinitions": {
            "apiKey": {
                "type": "apiKey",
                "in": "header",
                "description": "Value for the Authorization header",
                "name": "Authorization"
            }
        },
        "security": [
            {
                "apiKey": []
            }
        ]
    }

1 Answer 1

1

You have to do that in the entity. You must have ApiResource annotation so you can add custom operations there. In this case, you have to put this annotation:

 *          "api_healthcheck_entrypoint"={
 *              "controller"=HealthcheckControllerAction::class,
 *              "method"="GET",
 *              "path"="/api/ping
 *              "defaults"={"_api_receive"=false},",
 *              "normalization_context"={
 *                  "groups"={"ping"}
 *              }

https://api-platform.com/docs/core/operations/#creating-custom-operations-and-controllers

Sign up to request clarification or add additional context in comments.

2 Comments

So... Why are you using API Platform if you are not following his philosophy? If you check the documentation, you have 3 ways for do this: * Annotations in the entity * XML * yaml but not in the controller...
You don't necessarily need an Entity but you do need a class to set as resource. See the General Design Considerations. Also see Aperation without entity and How to write custom endpoints with parameters.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.