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)
A Django api to display items and their current up-to-date prices from different online retailers in one platform.

A Django api to display items and their current up-to-date prices from different online retailers in one platform. Utilizing scrapy to periodically scrape the latest prices from different online reta

Kennedy Ngugi Mwaura 1 Nov 05, 2021
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
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
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
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
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
Scaffold django rest apis like a champion 🚀

scaffold django rest apis like a champion 🚀

Abdenasser Elidrissi 133 Jan 05, 2023
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 simple API example in Python (Flask framework)

API-Example A simple API in Python(Flask) ✨ Features An API i guess? 💁‍♀️ How to use first download the main.py install python then install flask fra

Portgas D Ace 2 Jan 06, 2022
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
Recursive Serialization for Django REST framework

djangorestframework-recursive Overview Recursive Serialization for Django REST framework This package provides a RecursiveField that enables you to se

336 Dec 28, 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 04, 2023
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
simple api build with django rest framework

Django Rest API django-rest-framework Employees management simple API in this project wrote test suites for endpoints wrote simple doc string for clas

OMAR.A 1 Mar 31, 2022
Integrate GraphQL into your Django project.

Graphene-Django A Django integration for Graphene. 💬 Join the community on Slack Documentation Visit the documentation to get started! Quickstart For

GraphQL Python 4k Dec 31, 2022
Sanic-RESTPlus is an extension for Sanic that adds support for quickly building REST APIs.

Sanic RestPlus Sanic-RESTPlus is an extension for Sanic that adds support for quickly building REST APIs. Sanic-RESTPlus encourages best practices wit

Ashley Sommer 106 Oct 14, 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
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-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