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
 
  1. 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
 
  1. @request.restful()
  2. def api():
  3. response.view = 'generic.'+request.extension
  4. def GET(*args,**vars):
  5. patterns = 'auto'
  6. parser = db.parse_as_rest(patterns,args,vars)
  7. if parser.status == 200:
  8. return dict(content=parser.response)
  9. else:
  10. raise HTTP(parser.status,parser.error)
  11. def POST(table_name,**vars):
  12. return db[table_name].validate_and_insert(**vars)
  13. def PUT(table_name,record_id,**vars):
  14. return db(db[table_name]._id==record_id).update(**vars)
  15. def DELETE(table_name,record_id):
  16. return db(db[table_name]._id==record_id).delete()
  17. 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 
 
  1. auth.settings.allow_basic_login = True
  2. @auth.requires_login()
above @request.restful. Authentification now is mandatory for the REST interface.
 
10. get the first entry
 
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:
 
  1. import requests
  2. from requests.auth import HTTPBasicAuth
  3. payload = {'f_entry': 'somevalue'}
  4. auth=HTTPBasicAuth('user', 'pass')
  5. r = requests.post("http://127.0.0.1:8000/RT/default/api/entries.json", data=payload, auth=auth)
  6. r = requests.delete("http://127.0.0.1:8000/RT/default/api/entries/1.json", data=payload, auth=auth)

Comentários

Postagens mais visitadas deste blog

Web2py com NGINX

Configurar o web2py no Apache e Ubuntu LTS