Py4Web Rest API Test

377 views
Skip to first unread message

Kevin Keller

unread,
Jul 26, 2019, 5:49:28 AM7/26/19
to web2py-users
Hello, 

this is in my controller: 

from pydal.restapi import RestAPI, Policy

policy = Policy()
policy.set('superhero', 'GET', authorize=True, allowed_patterns=['*'])
policy.set('*', 'GET', authorize=True, allowed_patterns=['*'])
policy.set('*', 'PUT', authorize=False)
policy.set('*', 'POST', authorize=False)
policy.set('*', 'DELETE', authorize=False)

@action('rest', method='GET')
def api():
    return RestAPI(db, policy)(request.method, request.args(0), request.args(1),
                             request.get_vars, request.post_vars)


and this in my models.py. 

db.define_table(
    'person',
    Field('name'),
    Field('job'))

db.define_table(
    'superhero',
    Field('name'),
    Field('real_identity', 'reference person'))

db.define_table(
    'superpower',
    Field('description'))

db.define_table(
    'tag',
    Field('superhero', 'reference superhero'),
    Field('superpower', 'reference superpower'),
    Field('strength', 'integer'))


But I get 404 no matter how I try to access... 

/test/rest/api.json/superhero?name.eq=Superman

Also had to change the import from the docs from dbapi to restapi.. 

Massimo Di Pierro

unread,
Jul 27, 2019, 2:33:14 AM7/27/19
to web2py-users
You have a perfect example of web2py vs py4web.

Almost everything in your code works in both web2py and py4web but you action is a mix of both and works in neither.

@action('rest', method='GET') # this is py4web syntax only defined the
def api():
    return RestAPI(db, policy)(request.method, request.args(0), request.args(1), request.get_vars, request.post_vars) # this is web2py syntax

In py4web there is no request.args, request.get_vars and request.post_vars and you have to use the bottle syntax:

@action('rest/<tablename>')
@action('rest/<tablename>/<id>')
def api(tablename, id=None):
    return RestAPI(db, policy)(request.method, tablename, id, request.query, request.json)

This will expose /{appname}/rest/{tablename} and /{appname}/rest/{tablename}/{id}


Reply all
Reply to author
Forward
0 new messages