This is my first attempt at designing a web application. I have created a CRUD operating API for a SQLAlchemy database. I am now trying to design a RESTful web framework using Pyramid to support this DB and all its entities.
I have been struggling on how to PUT (update). I know there are certain conditions that I also need to incorporate (e.g. Code 202). I am uncertain on how to handle the object replacement using PUT. The method in the view configuration is a bit confusing and I believe I am following the db CRUD operations.
Secondly, I believe that all resources have to be looked up via {id}. I believe I have this correct in the get_user method. User_id holds all the information of the user in the db...so, if a user is looked up by id, than I shouldn't need to have all the other information (see delete_user method).
I have read some nifty tutorials on designing a RESTful design, but I am still struggling given that I am self taught. Your help is truly appreciated!
Here is an example of some code that shows the problem:
_ init _.py (URIs):
config.add_route('post_user', '/users') # POST (HTTP) / CREATE (CRUD)
config.add_route('get_user', '/users/{id}') #GET (HTTP) / RETRIEVE (CRUD)
config.add_route('put_user', '/users/{id}') # PUT (HTTP) / UPDATE (CRUD)
config.add_route('delete_user', '/users/{id}') # DELETE (HTTP) / DELETE (CRUD)
views.py (view config -- RESTful):
@view_defaults(renderer='json')
class RESTView(object):
api = ConvenienceAPI() # CRUD API for database
def __init__(self, request):
self.request = request
@view_config(route_name='get_user', request_method='GET')
def get_user(self):
user_id = int(request.matchdict['user_id'])
user = api.retrieve_user('user_id')
if user is None:
raise HTTPNotFound()
else:
return user
@view_config(route_name='post_user', request_method='POST')
def post_user(self):
username = request.matchdict['username']
password = request.matchdict['password']
firstname = request.matchdict['firstname']
lastname = request.matchdict['lastname']
email = request.matchdict['email']
new_user = api.create_user('username', 'password', 'firstname', 'lastname', 'email')
return Response{'new_user': user}
@view_config(route_name='put_user', request_method='PUT')
def put_user(self):
user = request.matchdict['user_id']
new_username = # is this pointing to another URL ????
updated_user = api.update_user('username', 'new_username')
return Response{status='202 Accepted'}
@view_config(route_name='delete_user', request_method='DELETE')
def delete_user(self):
user = request.matchdict['user_id']
del_user = api.delete_user('username', 'firstname', 'lastname')
return Response{'del_user': user}