Пример реализации 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

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

Python

import requests
import json


def main():
    url = "https://specialistoff.net/api"
    headers = {'content-type': 'application/json'}

    # Example echo method
    payload = {
        "method": "questions",
        "params": {"page":1},
        "jsonrpc": "2.0",
        "id": 0,
    }
    response = requests.post(
        url, data=json.dumps(payload), headers=headers).json()

    print( response["result"] )

if __name__ == "__main__":
    main()