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)
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
Scaffold django rest apis like a champion 🚀

scaffold django rest apis like a champion 🚀

Abdenasser Elidrissi 133 Jan 05, 2023
A RESTful way to use your Notion tables as a database.

rest-notion-db A RESTful way to use your Notion tables as a database. Use-cases Form submissions or frontend websites, use one database that

Oorjit Chowdhary 42 Dec 27, 2022
Dropdown population implementation for Django REST Framework

drf-dropdown Dropdown population implementation for Django REST Framework Usage Add DropdownView to API URL # urls.py import dropdown urlpatterns = [

Preeti Yuankrathok 4 Dec 06, 2022
DSpace REST API Client Library

DSpace Python REST Client Library This client library allows Python 3 scripts (Python 2 probably compatible but not officially supported) to interact

The Library Code GmbH 10 Nov 21, 2022
Document Web APIs made with Django Rest Framework

DRF Docs Document Web APIs made with Django Rest Framework. View Demo Contributors Wanted: Do you like this project? Using it? Let's make it better! S

Manos Konstantinidis 626 Nov 20, 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
The no-nonsense, minimalist REST and app backend framework for Python developers, with a focus on reliability, correctness, and performance at scale.

The Falcon Web Framework Falcon is a reliable, high-performance Python web framework for building large-scale app backends and microservices. It encou

Falconry 9k Jan 03, 2023
Python bindings for Podman's RESTful API

podman-py This python package is a library of bindings to use the RESTful API of Podman. It is currently under development and contributors are welcom

Containers 142 Jan 06, 2023
Transparently use webpack with django

Looking for maintainers This repository is unmaintained as I don't have any free time to dedicate to this effort. If you or your organisation are heav

2.4k Dec 24, 2022
Turn your API made with Django REST Framework(DRF) into a GraphQL like API.

Turn your API made with Django REST Framework(DRF) into a GraphQL like API.

Yezy Ilomo 575 Jan 05, 2023
A lightweight REST miniframework for Python.

restless A lightweight REST miniframework for Python. Documentation is at https://restless.readthedocs.io/. Works great with Django, Flask, Pyramid, T

Daniel Lindsley 824 Nov 20, 2022
Example Starlette REST API application

The idea of this project is to show how Starlette, Marshmallow, and SQLAlchemy can be combined to create a RESTful HTTP API application that is modular, lightweight, and capable of dealing with many

Robert Wikman 0 Jan 07, 2022
Generate Views, Serializers, and Urls for your Django Rest Framework application

DRF Generators Writing APIs can be boring and repetitive work. Don't write another CRUDdy view in Django Rest Framework. With DRF Generators, one simp

Tobin Brown 332 Dec 17, 2022
One package to access multiple different data sources through their respective API platforms.

BESTLab Platform One package to access multiple different data sources through their respective API platforms. Usage HOBO Platform See hobo_example.py

Wei 1 Nov 16, 2021
JSON:API support for Django REST framework

JSON:API and Django REST framework Overview JSON:API support for Django REST framework Documentation: https://django-rest-framework-json-api.readthedo

1k Dec 27, 2022
Kong API Manager with Prometheus And Splunk

API Manager Stack Run Kong Server + Konga + Prometheus + Grafana + API & DDBB + Splunk Clone the proyect and run docker-compose up

Santiago Fernandez 82 Nov 26, 2022
A small project in Python + Flask to demonstrate how to create a REST API

SmartBed-RESTApi-Example This application is an example of how to build a REST API. The application os a mock IoT device, simulating a Smart Bed. Impl

Rares Cristea 6 Jan 28, 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 app for handling the server headers required for Cross-Origin Resource Sharing (CORS)

django-cors-headers A Django App that adds Cross-Origin Resource Sharing (CORS) headers to responses. This allows in-browser requests to your Django a

Adam Johnson 4.8k Jan 05, 2023