API RESTFul no web2py
Este artigo é uma cópia do original em http://www.web2pyslices.com/slice/show/1533/restful-api-with-web2py
acessado em 06/04/2021 18:55
autor Bruno Rocha
Hi,
1. Create an app in web2py admin panel
2. In models/db.py define a table named entries
- Entries = db.define_table("entries", Field("entry", "text"))
3. Register a new user in http://localhost:8000/myapp/default/user/register
4. Go to appadmin http://localhost:8000/myapp/appadmin and Add a couple of entries.
5. now add the RESTful services to the default.py controller as described in http://goo.gl/iITNd ('parse_as_rest') or here: http://goo.gl/ltfa2
- @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)
- def PUT(table_name,record_id,**vars):
- return db(db[table_name]._id==record_id).update(**vars)
- def DELETE(table_name,record_id):
- return db(db[table_name]._id==record_id).delete()
- return dict(GET=GET, POST=POST, PUT=PUT, DELETE=DELETE)
6. In the browser:
you get all entries with
7. you get the just the second entry with
8. you get all auto-generated patterns with
That's as far as we get with GET in a browser.
9. To make things more realistic, we add basic user authentication and try some POSTs with curl.
- Add
- auth.settings.allow_basic_login = True
- @auth.requires_login()
above @request.restful. Authentification now is mandatory for the REST interface.
10. get the first entry
curl --user user:pass http://127.0.0.1:8000/RT/ default/api/entries/id/1.json
11. post a new entry
curl --user user:pass -d "f_entry=something" http://127.0.0.1:8000/RT/ default/api/entries.json
12. delete the first entry
curl -X DELETE --user user:pass http://127.0.0.1:8000/RT/ default/api/entries/1.json
13. Same thing from python:
- import requests
- from requests.auth import HTTPBasicAuth
- payload = {'f_entry': 'somevalue'}
- auth=HTTPBasicAuth('user', 'pass')
- r = requests.post("http://127.0.0.1:8000/RT/default/api/entries.json", data=payload, auth=auth)
- r = requests.delete("http://127.0.0.1:8000/RT/default/api/entries/1.json", data=payload, auth=auth)
Comentários
Postar um comentário