Sanic-RESTPlus is an extension for Sanic that adds support for quickly building REST APIs.

Overview

Sanic RestPlus

Sanic-RESTPlus is an extension for Sanic that adds support for quickly building REST APIs. Sanic-RESTPlus encourages best practices with minimal setup. If you are familiar with Sanic, Sanic-RESTPlus should be easy to pick up. It provides a coherent collection of decorators and tools to describe your API and expose its documentation properly using Swagger.

Compatibility

  • Sanic-RestPlus requires Python 3.7+.
  • Sanic-RestPlus works with Sanic v21.3+

Important Compatibility Notice

Sanic-RestPlus version 0.6.0 was reworked and now requires Sanic v21.3 or later.

Sanic-RestPlus version 0.4.1 (and previous versions) does not work on Sanic 19.12+, see this bug here: https://github.com/ashleysommer/sanicpluginsframework/issues/15

Please use Sanic-Restplus v0.5.x if you need to deploy on Sanic v19.12 or v20.12

If you are using the Sanic v20.12LTS, please use Sanic-RestPlus v0.5.6.

Installation

In the near future, you will be able to install Sanic-Restplus with pip:

$ pip install sanic-restplus

or with easy_install:

$ easy_install sanic-restplus

Quick start

With Sanic-Restplus, you only import the api instance to route and document your endpoints.

') @ns.response(404, 'Todo not found') @ns.param('id', 'The task identifier') class Todo(Resource): '''Show a single todo item and lets you delete them''' @ns.doc('get_todo') @ns.marshal_with(todo) async def get(self, request, id): '''Fetch a given resource''' return DAO.get(id) @ns.doc('delete_todo') @ns.response(204, 'Todo deleted') async def delete(self, request, id): '''Delete a task given its identifier''' DAO.delete(id) return '', 204 @ns.expect(todo) @ns.marshal_with(todo) async def put(self, request, id): '''Update a task given its identifier''' return DAO.update(id, request.json) rest_assoc.api(api) if __name__ == '__main__': app.run(debug=True, auto_reload=False) ">
from sanic import Sanic
from sanic_restplus import Api, Resource, fields
from sanic_restplus.restplus import restplus
from sanic_plugin_toolkit import SanicPluginRealm
app = Sanic(__name__)
realm = SanicPluginRealm(app)
rest_assoc = realm.register_plugin(restplus)

api = Api(version='1.0', title='TodoMVC API',
          description='A simple TodoMVC API')

ns = api.namespace('todos', description='TODO operations')

todo = api.model('Todo', {
    'id': fields.Integer(readOnly=True, description='The task unique identifier'),
    'task': fields.String(required=True, description='The task details')
})


class TodoDAO(object):
    def __init__(self):
        self.counter = 0
        self.todos = []

    def get(self, id):
        for todo in self.todos:
            if todo['id'] == id:
                return todo
        api.abort(404, "Todo {} doesn't exist".format(id))

    def create(self, data):
        todo = data
        todo['id'] = self.counter = self.counter + 1
        self.todos.append(todo)
        return todo

    def update(self, id, data):
        todo = self.get(id)
        todo.update(data)
        return todo

    def delete(self, id):
        todo = self.get(id)
        self.todos.remove(todo)


DAO = TodoDAO()
DAO.create({'task': 'Build an API'})
DAO.create({'task': '?????'})
DAO.create({'task': 'profit!'})


@ns.route('/')
class TodoList(Resource):
    '''Shows a list of all todos, and lets you POST to add new tasks'''

    @ns.doc('list_todos')
    @ns.marshal_list_with(todo)
    async def get(self, request):
        '''List all tasks'''
        return DAO.todos

    @ns.doc('create_todo')
    @ns.expect(todo)
    @ns.marshal_with(todo, code=201)
    async def post(self, request):
        '''Create a new task'''
        return DAO.create(request.json), 201


@ns.route('/
     
      '
     )
@ns.response(404, 'Todo not found')
@ns.param('id', 'The task identifier')
class Todo(Resource):
    '''Show a single todo item and lets you delete them'''

    @ns.doc('get_todo')
    @ns.marshal_with(todo)
    async def get(self, request, id):
        '''Fetch a given resource'''
        return DAO.get(id)

    @ns.doc('delete_todo')
    @ns.response(204, 'Todo deleted')
    async def delete(self, request, id):
        '''Delete a task given its identifier'''
        DAO.delete(id)
        return '', 204

    @ns.expect(todo)
    @ns.marshal_with(todo)
    async def put(self, request, id):
        '''Update a task given its identifier'''
        return DAO.update(id, request.json)

rest_assoc.api(api)

if __name__ == '__main__':
    app.run(debug=True, auto_reload=False)

Documentation

The documentation is hosted on Read the Docs That is the Flask RestPlus documentation, the Sanic-Restplus docs are not converted yet.

Comments
  • Sanic-restplus is not avilable on pypi

    Sanic-restplus is not avilable on pypi

    pip install sanic-restplus Collecting sanic-restplus Could not find a version that satisfies the requirement sanic-restplus (from versions: ) No matching distribution found for sanic-restplus

    opened by manuelsotoma 6
  • Multiple values for

    Multiple values for "url_prefix"

    I've been having a hard time using Blueprints with sanic_restplus, and am wondering if this is just an area that is in progress? My own code is giving an error about multiple values for the argument "url_prefix" even though it's only defined once, in one blueprint definition.

    To rule out my code, I tried to run the example "todo_blueprint", changing Flask to Sanic, and I'm getting the same result:

    Traceback (most recent call last): File "test.py", line 4, in api_v1 = Blueprint('api', name, url_prefix='/api/1') TypeError: init() got multiple values for argument 'url_prefix'

    Has anyone seen this? Thanks in advance for help you might be able to offer. Sanic-Restplus is clearly the right way to go for building REST APIs on Sanic, but I haven't gotten multiple API versions and blueprints working yet....

    opened by madsenwattiq 5
  • TypeError: __new__() missing 1 required positional argument: 'version_prefix'

    TypeError: __new__() missing 1 required positional argument: 'version_prefix'

    Hi, I currently use python3.7, sanic 21.6.2 and sanic-restplus 0.6.0. When I run my project, I got a type error as below:

    File "/Users/jailge/PycharmProjects/eslogsystem/sanic-ls-service/venv/lib/python3.7/site-packages/sanic_plugin_toolkit/realm.py", line 350, in _plugin_register_app_route fr = SanicFutureRoute(r_handler, uri, name=name, **kwargs) TypeError: __new__() missing 1 required positional argument: 'version_prefix'

    opened by jailge 4
  • Requires version_prefix in FutureRoute

    Requires version_prefix in FutureRoute

    PR https://github.com/sanic-org/sanic/pull/2137 added a new route requirement of version_prefix This patch fixes the API so that it supplies that value if the FutureRoute has the attribute. It is also backwards compatble.

    opened by notzippy 4
  • sanic-restplus breaks on sanic 19.12.2

    sanic-restplus breaks on sanic 19.12.2

    Run the quick start example on Sanic 19.12.2 and got this error message:

    [2020-01-28 07:26:29 +0200] [53084] [INFO] Goin' Fast @ http://127.0.0.1:8000
    [2020-01-28 07:26:29 +0200] [53084] [INFO] Starting worker [53084]
    KeyError('PROPAGATE_EXCEPTIONS')
    [2020-01-28 07:26:31 +0200] [53084] [ERROR] Exception occurred while handling uri: 'http://localhost:8000/todos'
    Traceback (most recent call last):
      File "/Users/db/venvs/untitled3/lib/python3.7/site-packages/sanic/app.py", line 946, in handle_request
        request, request_name=name
    TypeError: _run_request_middleware() got an unexpected keyword argument 'request_name'
    [2020-01-28 07:26:31 +0200] - (sanic.access)[INFO][127.0.0.1:49633]: GET http://localhost:8000/todos  500 144
    
    opened by DavidBord 4
  • Fix the import error by falling back to earlier sanic versions

    Fix the import error by falling back to earlier sanic versions

    Fixes the broken import following the import pattern applied here: https://github.com/ashleysommer/sanic-cors/commit/187726f81493dc0d2974bc67597cb9786324c02b

    Also fixes #12

    opened by MihaiBalint 4
  • One letter in dictionary:value fixing / reqparse fixing

    One letter in dictionary:value fixing / reqparse fixing

    When you parse a request, it turns out that the result is a dictionary of the form

    {
        "key": "v",
    }
    

    although there was a dictionary

    {
        "key": "value",
    }
    

    in the request.


    Replacing [(k,a) for k,v in value.items() for a in v] on simple values.items() in CIMultiDict(...) should help.

    opened by kzagorulko 3
  • Using v0.5.6 for Sanic 20.12.* causes dependency issue

    Using v0.5.6 for Sanic 20.12.* causes dependency issue

    Currently using Sanic 20.12.3 and am limited form upgrading to v21, thus was trying to use sanic-restplus 0.5.6 as recommended. But I run run into the following dependency issue:

    There are incompatible versions in the resolved dependencies:
      sanic==20.12.3 (from -r /tmp/pipenv8pobw9kgrequirements/pipenv-s50m307i-constraints.txt (line 17))
      sanic<21,>=18.12.0 (from sanic-plugins-framework==0.9.5->sanic-restplus==0.5.6->-r /tmp/pipenv8pobw9kgrequirements/pipenv-s50m307i-constraints.txt (line 6))
      sanic<21,>=18.12.0 (from sanic-restplus==0.5.6->-r /tmp/pipenv8pobw9kgrequirements/pipenv-s50m307i-constraints.txt (line 6))
      sanic>=18.12 (from sanic-jinja2-spf==0.8.0->sanic-restplus==0.5.6->-r /tmp/pipenv8pobw9kgrequirements/pipenv-s50m307i-constraints.txt (line 6))
      sanic>=21.3 (from sanic-jinja2==0.10.0->sanic-jinja2-spf==0.8.0->sanic-restplus==0.5.6->-r /tmp/pipenv8pobw9kgrequirements/pipenv-s50m307i-constraints.txt (line 6))
    

    Any recommendations/fixes?

    opened by kirisanth-g 2
  • The 'sanic_restplus.api' package was not installed in a way that PackageLoader understands

    The 'sanic_restplus.api' package was not installed in a way that PackageLoader understands

    win10,sanic 20.12.3,sanic-restplus 0.5.6

    I got the value error as below:

    Traceback (most recent call last):
      File "app/__main__.py", line 12, in <module>
        main(sys.argv[1:])
      File "app/__main__.py", line 8, in main
        app(argv)
      File "C:\Users\hsz12\Documents\WORKSPACE\project_manager_with_git\tp_py_sanic_api\env\lib\site-packages\schema_entry\entrypoint.py", line 204, in __call__
        self.parse_args(parser, argv)
      File "C:\Users\hsz12\Documents\WORKSPACE\project_manager_with_git\tp_py_sanic_api\env\lib\site-packages\schema_entry\entrypoint.py", line 451, in parse_args
        self.do_main()
      File "C:\Users\hsz12\Documents\WORKSPACE\project_manager_with_git\tp_py_sanic_api\app\app.py", line 92, in do_main
        rest_assoc.api(api)
      File "C:\Users\hsz12\Documents\WORKSPACE\project_manager_with_git\tp_py_sanic_api\env\lib\site-packages\sanic_restplus\restplus.py", line 10, in api
        return plug.api(reg, *args, api_class=api_class, **kwargs)
      File "C:\Users\hsz12\Documents\WORKSPACE\project_manager_with_git\tp_py_sanic_api\env\lib\site-packages\sanic_restplus\restplus.py", line 76, in api
        api.init_api(reg, **kwargs)
      File "C:\Users\hsz12\Documents\WORKSPACE\project_manager_with_git\tp_py_sanic_api\env\lib\site-packages\sanic_restplus\api.py", line 225, in init_api
        self._init_app(app, context)
      File "C:\Users\hsz12\Documents\WORKSPACE\project_manager_with_git\tp_py_sanic_api\env\lib\site-packages\sanic_restplus\api.py", line 235, in _init_app
        render_api_fn = self._setup_jinja2_renderer()
      File "C:\Users\hsz12\Documents\WORKSPACE\project_manager_with_git\tp_py_sanic_api\env\lib\site-packages\sanic_restplus\api.py", line 282, in _setup_jinja2_renderer
        loader = PackageLoader(__name__, 'templates')
      File "C:\Users\hsz12\Documents\WORKSPACE\project_manager_with_git\tp_py_sanic_api\env\lib\site-packages\jinja2\loaders.py", line 309, in __init__
        raise ValueError(
    ValueError: The 'sanic_restplus.api' package was not installed in a way that PackageLoader understands.
    
    opened by hsz1273327 2
  • Fail installing dependencies to develop (pip install -e .[dev])

    Fail installing dependencies to develop (pip install -e .[dev])

    Hi! I cannot install the dependencies in file requirements/develop.pip. When I run the pip install -e .[dev] command, pip returns the following output:

    sanic-restplus 0.3.1.dev20180411 does not provide the extra 'dev'

    Running with other options (test and doc) works perfectly.

    opened by abispo 2
  • fixing reqparse for sanic Requests object / differs from flask Reques…

    fixing reqparse for sanic Requests object / differs from flask Reques…

    When trying to parse arguments on the requests, it previously failed trying to access the value key in the request (Which doesn't seem to exists on a Sanic request). Replacing with "args" instead of "value" did fix the issues for that. Then adding the (key:value) tuples to the multi-dict at the source level fixed the rest.

    opened by oliverpain 1
  • Multiple swagger docs

    Multiple swagger docs

    Is it possible with the current release (0.5.5) to support multiple swagger endpoints? I tried to register an two Api instances and it failed on the second, with a sanic.router.RouteExists: Route already registered: /swaggerui<file_uri:/?.+> [HEAD,GET] I noticed on issue #6 you had mentioned using blueprints was disabled but that does appear that the only way you can enable multiple Api documents in the restplus plugin for flask. Is there another way?

    thanks

    opened by notzippy 1
Releases(v0.6.1)
Async Python 3.6+ web server/framework | Build fast. Run fast.

Sanic | Build fast. Run fast. Build Docs Package Support Stats Sanic is a Python 3.6+ web server and web framework that's written to go fast. It allow

Sanic Community Organization 16.7k Dec 28, 2022
Country-specific Django helpers, to use in Django Rest Framework

django-rest-localflavor Country-specific serializers fields, to Django Rest Framework Documentation (soon) The full documentation is at https://django

Gilson Filho 19 Aug 30, 2022
Little Library API REST

Little Library API REST py 3.10 The only one requeriment it's to have Flask installed.

Luis Quiñones Requelme 1 Dec 15, 2021
Django-rest-auth provides a set of REST API endpoints for Authentication and Registration

This app makes it extremely easy to build Django powered SPA's (Single Page App) or Mobile apps exposing all registration and authentication related functionality as CBV's (Class Base View) and REST

Tivix 2.4k Dec 29, 2022
Django REST API with React BoilerPlate

This is a setup of Authentication and Registration Integrated with React.js inside the Django Templates for web apps

Faisal Nazik 91 Dec 30, 2022
Django queries

Djaq Djaq - pronounced “Jack” - provides an instant remote API to your Django models data with a powerful query language. No server-side code beyond t

Paul Wolf 53 Dec 12, 2022
RESTful Todolist API

RESTful Todolist API GET todolist/ POST todolist/ {"desc" : "Description of task to do"} DELETE todolist/int:id PUT todolist/int:id Requirements D

Gabriel Tavares 5 Dec 20, 2021
A Django-powered API with various utility apps / endpoints.

A Django-powered API Includes various utility apps / endpoints. Demos These web apps provide a frontend to the APIs in this project. Issue API Explore

Shemar Lindie 0 Sep 13, 2021
RESTler is the first stateful REST API fuzzing tool for automatically testing cloud services through their REST APIs and finding security and reliability bugs in these services.

RESTler is the first stateful REST API fuzzing tool for automatically testing cloud services through their REST APIs and finding security and reliability bugs in these services.

Microsoft 1.8k Jan 04, 2023
Mlflow-rest-client - Python client for MLflow REST API

Python Client for MLflow Python client for MLflow REST API. Features: Minimal de

MTS 35 Dec 23, 2022
Extensions for Django REST Framework

Extensions for Django REST Framework

aiden 6 Dec 27, 2022
A light REST library for Django.

django-nap Read The Docs: https://django-nap.readthedocs.io/en/latest/ Change log: https://django-nap.readthedocs.io/en/latest/changelog.html An API l

Curtis Maloney 223 Dec 07, 2022
Authentication Module for django rest auth

django-rest-knox Authentication Module for django rest auth Knox provides easy to use authentication for Django REST Framework The aim is to allow for

James McMahon 873 Dec 30, 2022
a web-remote minecraft server wrapper with some unique features

Canceled here, continued as Semoxy MCWeb - a Minecraft Server Web Interface MCWeb is a web-remote Minecraft Server Wrapper for controlling your Minecr

Anton Vogelsang 1 Jul 12, 2021
Embrace the APIs of the future. Hug aims to make developing APIs as simple as possible, but no simpler.

Read Latest Documentation - Browse GitHub Code Repository hug aims to make developing Python driven APIs as simple as possible, but no simpler. As a r

Hug API Framework 6.7k Dec 27, 2022
Scaffold django rest apis like a champion 🚀

scaffold django rest apis like a champion 🚀

Abdenasser Elidrissi 133 Jan 05, 2023
A RESTful whois

whois-rest A RESTful whois. Installation $ pip install poetry $ poetry install $ uvicorn app:app INFO: Started server process [64616] INFO: W

Manabu Niseki 4 Feb 19, 2022
Estudo e desenvolvimento de uma API REST

Estudo e desenvolvimento de uma API REST 🧑‍💻 Tecnologias Esse projeto utilizará as seguintes tecnologias: Git Python Flask DBeaver Vscode SQLite 🎯

Deusimar 7 May 30, 2022
Key-Value база данных на Tarantool и REST API к ней.

KVmail Key-Value база данных на Tarantool и REST API к ней. Документация к API доступна здесь. Requiremrnts ubuntu 16.04+ python3.6+ supervisord nginx

1 Jun 16, 2021