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)
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
Creating delicious APIs for Django apps since 2010.

django-tastypie Creating delicious APIs for Django apps since 2010. Currently in beta but being used actively in production on several sites. Requirem

3.8k Dec 30, 2022
Eazytraining - Simple application to show how to query API from webapp

student-list Eazytraining - Simple application to show how to query API from webapp This repo is a simple application to list student with a webserver

⚡Christophe FREIJANES 2 Nov 15, 2021
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
Flask RestAPI Project - Transimage Rest API For Python

[ 이미지 변환 플라스크 Rest API ver01 ] 0. Flask Rest API - in SunnyWeb : 이미지 변환 웹의 Flask

OliverKim 1 Jan 12, 2022
FastAPI framework, high performance, easy to learn, fast to code, ready for production

FastAPI framework, high performance, easy to learn, fast to code, ready for production Documentation: https://fastapi.tiangolo.com Source Code: https:

Sebastián Ramírez 53.1k Jan 06, 2023
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
Key-Value база данных на Tarantool и REST API к ней.

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

1 Jun 16, 2021
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
Simplified REST API to get stickers from Snap

Snap Sticker kit REST API Simplified REST API to get stickers from Snap 💻 Instructions Search stickers Request: url = "https://sticker-kit-horizon733

Dishant Gandhi 1 Jan 05, 2022
Built on Django Rest Framework, to provide with command execution on linux terminal

Built on Django Rest Framework, to provide with command execution on linux terminal

1 Oct 31, 2021
REST implementation of Django authentication system.

djoser REST implementation of Django authentication system. djoser library provides a set of Django Rest Framework views to handle basic actions such

Sunscrapers 2.2k Jan 01, 2023
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
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
Build a Backend REST API with Python & Django

Build a Backend REST API with Python & Django Skills Python Django djangorestframework Aws Git Use the below Git commands in the Windows Command Promp

JeonSoohyun a.k.a Edoc.. 1 Jan 25, 2022
Django Ninja is a web framework for building APIs with Django and Python 3.6+ type hints.

💨 Fast, Async-ready, Openapi, type hints based framework for building APIs

Vitaliy Kucheryaviy 3.8k Jan 04, 2023
A small repository of projects built in my course, REST APIs with Flask and Python.

A small repository of projects built in my course, REST APIs with Flask and Python.

Teclado 1k Jan 05, 2023
Eureka is a Rest-API framework scraper based on FastAPI for cleaning and organizing data, designed for the Eureka by Turing project of the National University of Colombia

Eureka is a Rest-API framework scraper based on FastAPI for cleaning and organizing data, designed for the Eureka by Turing project of the National University of Colombia

Julian Camilo Velandia 3 May 04, 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
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