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

scaffold django rest apis like a champion ??

Abdenasser Elidrissi 133 Jan 5, 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
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 (JSON)

Tivix 2.4k Dec 29, 2022
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
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

null 1k Dec 27, 2022
Browsable web APIs for Flask.

Flask API Browsable web APIs for Flask. Status: This project is in maintenance mode. The original author (Tom Christie) has shifted his focus to API S

Flask API 1.3k Dec 27, 2022
Web APIs for Django. 🎸

Django REST framework Awesome web-browsable Web APIs. Full documentation for the project is available at https://www.django-rest-framework.org/. Fundi

Encode 24.7k Jan 4, 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

null 3.8k Dec 30, 2022
REST API framework designed for human beings

Eve Eve is an open source Python REST API framework designed for human beings. It allows to effortlessly build and deploy highly customizable, fully f

eve 6.6k Jan 4, 2023
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 3, 2023
Authentication for Django Rest Framework

Dj-Rest-Auth Drop-in API endpoints for handling authentication securely in Django Rest Framework. Works especially well with SPAs (e.g React, Vue, Ang

Michael 1.1k Dec 28, 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
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 1, 2023
A JSON Web Token authentication plugin for the Django REST Framework.

Simple JWT Abstract Simple JWT is a JSON Web Token authentication plugin for the Django REST Framework. For full documentation, visit django-rest-fram

Jazzband 3.3k Jan 4, 2023
Automated generation of real Swagger/OpenAPI 2.0 schemas from Django REST Framework code.

drf-yasg - Yet another Swagger generator Generate real Swagger/OpenAPI 2.0 specifications from a Django Rest Framework API. Compatible with Django Res

Cristi Vîjdea 3k Jan 6, 2023
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