You can do:

@request.restful()
def api():
    response.view = 'generic.json'
    def GET(tablename,id):
        if not tablename=='person': raise HTTP(400)
        return dict(person = db.person(id))
    def POST(tablename,**fields):
        if not tablename=='person': raise HTTP(400)
        return db.person.validate_and_insert(**fields)
    return locals()


and this:

@request.restful()
def api():
    response.view = 'generic.'+request.extension
    def GET(*args,**vars):
        patterns = [
            "/friends[person]",
            "/friend/{person.name.startswith}",
            "/friend/{person.name}/:field",
            "/friend/{person.name}/pets[pet.owner]",
            "/friend/{person.name}/pet[pet.owner]/{pet.name}",
            "/friend/{person.name}/pet[pet.owner]/{pet.name}/:field"
            ]
        parser = db.parse_as_rest(patterns,args,vars)
        if parser.status == 200:
            return dict(content=parser.response)
        else:
            raise HTTP(parser.status,parser.error)
    def POST(table_name,**vars):
        if table_name == 'person':
            return db.person.validate_and_insert(**vars)
        elif table_name == 'pet':
            return db.pet.validate_and_insert(**vars)
        else:
            raise HTTP(400)
    return locals()

$ curl -d "name=Tim" http://127.0.0.1:8000/myapp/default/api/friend.json
{"errors": {}, "id": 1}
$ curl http://127.0.0.1:8000/myapp/default/api/friends.json
{"content": [{"info": null, "name": "Tim", "id": 1}]}
$ curl -d "name=Snoopy&owner=1" http://127.0.0.1:8000/myapp/default/api/pet.json
{"errors": {}, "id": 1}
$ curl http://127.0.0.1:8000/myapp/default/api/friend/Tim/pet/Snoopy.json
{"content": [{"info": null, "owner": 1, "name": "Snoopy", "id": 1}]}

or even

@request.restful()
def api():
    response.view = 'generic.'+request.extension
    def GET(*args,**vars):
        patterns = 'auto'
        parser = db.parse_as_rest(patterns,args,vars)
        if parser.status == 200:
            return dict(content=parser.response)
        else:
            raise HTTP(parser.status,parser.error)
    def POST(table_name,**vars):
        return db[table_name].validate_and_insert(**vars)
    return locals()

call with for info

http://..../api/patterns.json




On Oct 12, 4:27 pm, Arturo Filastò <a...@baculo.org> wrote:
> I wish to implement a RESTful interface with web2py.
> What I would like to know is what is the most web2py friendly way of
> doing so.
>
> Is there a way to have the data inserted into the database without me
> having to write the queries myself?
>
> I am basically looking for the equivalent of
> forms.accepts(request.vars), but to be invoked from a web service.
>
> I already implemented what I basically want, but I think it is pretty
> ugly.
> You can my current implementation 
> here:https://github.com/globaleaks/GlobaLeaks/commit/4222890bf6cb7b96138c9...
>
> Any tips, suggestions?
>
> Thanks!
>
> - Art.

Reply via email to