3. Your API methods

Last modified by Ashterix on 2024/05/16 12:35

You can easily add your own API methods to the RPC server.

To do this, you just need to create any class that will become an API Service anywhere in your application. This class must implement the interface Ufo\JsonRpcBundle\ApiMethod\Interfaces\IRpcService. This interface does not impose any logic on the class; it is only necessary for Symfony to understand that it should treat it as a service available to the RPC server.

Implement any public method in your class, and it will automatically be available as an API Service.

 After following the previous instructions, new methods will already be available in the API. By default, method names are composed of <className>.<methodName>.

Naming Classes

If necessary, you can create several classes that will be available as API Services.
Considering their naming <className>.<methodName>, I recommend treating the method name as a simple indication of what it does and the class name as the namespace of the API method.

Best Practices

The class Messenger contains methods sendEmail(), sendSms(); the class CartResolver contains methods addProduct(), getProducts(), calculateDiscount().

In the API, the following methods will be available:

  • CartResolver.addProduct
  • CartResolver.getProducts
  • CartResolver.calculateDiscount
  • Messenger.sendEmail
  • Messenger.sendSms

Even just by looking at the method names, it is clear what your server can do.

This approach allows you to use the same method names in different classes:

  • ProductService.create
  • ProductService.getName
  • UserService.create
  • UserService.getName

Simple Start

The following example should demonstrate the ease of adding your methods to the API.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?php
namespace App\Api\Procedures;

use Ufo\JsonRpcBundle\ApiMethod\Interfaces\IRpcService;

class ExampleApi implements IRpcService
{
   public function __construct(
       // connecting some dependencies to retrieve data
   ) {}

   public function getUserNameByUuid(
        string $userId
    ): string {
       // some logic to get user info by id
       return 'some result';
    }

   public function sendEmail(
        string $email,
        string $text,
        string $subject = 'Message without subject'
    ): bool {
       // some logic to send email
       return true;
    }
}

To the right, you see an example of the documentation that the server will generate for this class.

The main information about parameter names, their types, and optionality is obtained thanks to ReflectionClass, with the important points being the order of method arguments and their type hints.

Documentation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
{
 "methods": {
     "ExampleApi.getUserNameByUuid": {
         "name": "ExampleApi.getUserNameByUuid",
         "description": "",
         "parameters": {
             "userId": {
                 "type": "string",
                 "name": "userId",
                 "description": "",
                 "optional": false
                }
            },
         "returns": "string",
         "responseFormat": "string"
        },
     "ExampleApi.sendEmail": {
         "name": "ExampleApi.sendEmail",
         "description": "",
         "parameters": {
             "email": {
                 "type": "string",
                 "name": "email",
                 "description": "",
                 "optional": false
                },
             "text": {
                 "type": "string",
                 "name": "text",
                 "description": "",
                 "optional": false
                },
             "subject": {
                 "type": "string",
                 "name": "subject",
                 "description": "",
                 "optional": true,
                 "default": "Message without subject"
                }
            },
         "returns": "boolean",
         "responseFormat": "boolean"
        }
    }
}

Now we can make POST requests to both new API methods and see the results.

POST Requests

Request
1
2
3
4
5
6
7
{
 "id": "example_request",
 "method": "ExampleApi.getUserNameByUuid",
 "params": {
     "userId": "1111"
    }
}
Response
1
2
3
4
5
{
 "id": "example_request",
 "result": "some result",
 "jsonrpc": "2.0"
}
Request
1
2
3
4
5
6
7
8
9
{
 "id": "example_request",
 "method": "ExampleApi.sendEmail",
 "params": {
     "email": "user@example.com",
     "subject": "This is a test mail",
     "text": "Hi! This is a test email sent by the API"
    }
}
Response
1
2
3
4
5
{
 "id": "example_request",
 "result": true,
 "jsonrpc": "2.0"
}

To simplify the documentation, all further examples will be provided using a single method (sendEmail).

Description of Methods and Parameters

The documenter relies on all available data belonging to the method and its arguments (names, input and output data types, docblocks). Thus, the description of methods and parameters can be enriched using docblocks.

Let's add a description for the method and its parameters.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?php
// ...
   /**
     * A method for sending an email message
     * @param string $email The email address
     * @param string $text Message body
     * @param string $subject Optional message subject parameter
     * @return bool
     */

   public function sendEmail(
        string $email,
        string $text,
        string $subject = 'Message without subject'
    ): bool {
       // some logic to send email
       return true;
    }
// ...

Note the documentation now displays additional information about the method and its parameters.

Documentation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
{
 "methods": {
     "ExampleApi.sendEmail": {
         "name": "ExampleApi.sendEmail",
         "description": "A method for sending an email message",
         "parameters": {
             "email": {
                 "type": "string",
                 "name": "email",
                 "description": "The email address",
                 "optional": false
                },
             "text": {
                 "type": "string",
                 "name": "text",
                 "description": "Message body",
                 "optional": false
                },
             "subject": {
                 "type": "string",
                 "name": "subject",
                 "description": "Optional message subject parameter",
                 "optional": true,
                 "default": "Message without subject"
                }
            },
         "returns": "boolean",
         "responseFormat": "boolean"
        }
    }
}

RPC Attributes

For more flexible customization of your API methods, JsonRpcBundle uses PHP attributes.

With the help of specialized attributes, you can:

  • set aliases for methods;
  • specify the response format for methods (if the response is in the form of an array, object, or collection of objects);
  • configure input parameter validation;
  • set up response caching.

Read more about these attributes: