Пример реализации API при помощи протокола JSON-RPC для Flask приложений



Код

from flask_jsonrpc import JSONRPC

jsonrpc = JSONRPC(app, '/api(name=str)')

@jsonrpc.method('tag.add')
def tag_add(name):
    """
    Добавление нового тега
    """
    tag = models.db_session.query(
        models.Tag
    ).filter(
        models.Tag.name==name.lower().strip()
    ).first()
    if tag:
        raise ValueError
    tag = models.Tag(name)
    models.db_session.add(tag)
    models.db_session.commit()
    return tag.as_dict()

Запрос

curl -i -X POST \
   -H "Content-Type: application/json; indent=4" \
   -d '{
    "jsonrpc": "2.0",
    "method": "tag.add",
    "params": {
        "name": "ci/cd"
    },
    "id": "9473cf76-e954-4833-8798-562bba031c40"
}' https://specialistoff.net/api

Ответ

{
    "id": "9473cf76-e954-4833-8798-562bba031c40",
    "jsonrpc": "2.0",
    "result": {
        "id": 412,
        "name": "ci/cd"
    }
}