public
Last active

RESTful controller with web.py

  • Download Gist
restful_app.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
import web
import json
from restful_controller import RESTfulController
 
urls = (
r'/resources(?:/(?P<resource_id>[0-9]+))?',
'ResourceController',
)
 
 
class ResourceController(RESTfulController):
 
def list(self):
return "list resources", format
 
def get(self, resource_id):
return "retrieved resource", resource_id
 
def create(self):
resource = json.loads(web.data())
return "created resource", resource
 
def update(self, resource_id):
resource = json.loads(web.data())
return "updated resource", resource_id, resource
 
def delete(self, resource_id):
return "deleted resource", resource_id
 
app = web.application(urls, globals())
 
if __name__ == "__main__":
app.run()
restful_controller.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
import web
 
 
class RESTfulController:
 
methods = ("list", "get", "create", "update", "delete",
"update_collection", "delete_collection")
 
def __getattr__(self, name):
if name in self.methods and "headers" in web.ctx:
raise web.badrequest()
else:
raise AttributeError
 
def GET(self, resource_id=None):
if resource_id is None:
return self.list()
else:
return self.get(resource_id)
 
def POST(self, resource_id=None):
if resource_id is None:
return self.create()
else:
raise web.badrequest()
 
def PUT(self, resource_id=None):
if resource_id is None:
return self.update_collection()
else:
return self.update(resource_id)
 
def DELETE(self, resource_id=None):
if resource_id is None:
return self.delete_collection()
else:
return self.delete(resource_id)

To create new resource

curl -X POST  -H "Content-Type: application/json" -d '{"title":"a title","description":"a description","type":"a type","author":"an author"}' -i http://localhost:8080/resources/

To update resource by id

curl -X PUT  -H "Content-Type: application/json" -d '{"id":"23", "title":"a title","description":"a description","type":"a type","author":"an author"}' -i http://localhost:8080/resources/23

To delete resource by id

curl -X DELETE http://localhost:8080/resources/23

A modified version of this code is used in this sample app https://github.com/w0rm/todo

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.