- Python tornado rest api
- 1. PyRestful library
- 2. Installation
- 3. Use: a demo for CRUD
- 3.1. Creating a new Customer
- 3.2. Read a Customer
- 3.3. Update a Customer
- 3.4. Delete a Customer
- Saved searches
- Use saved searches to filter your results more quickly
- rancavil/tornado-rest
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
Python tornado rest api
Before studying this article, you need:
- Be clear about the meaning of RESTful style (just understand, Demo will take you personal experience)
- Understand what Tornado is (yes, no development experience is required)
After studying this article, you can
- Use Tornado framework to quickly build REST-APIs
- Implement a CRUD (Create, Read, Update and Delete) operation process
1. PyRestful library
A Python component based on the Tornado framework to implement a RESTful API interface. In fact, it mainly provides
Four decorators, used to define a REST type of method().
Here is a simple Demo to tell you what it is (just follow @get).
import tornado.ioloop import pyrestful.rest from pyrestful import mediatypes from pyrestful.rest import get class EchoService(pyrestful.rest.RestHandler): @get(_path="/echo/", _produces=mediatypes.APPLICATION_JSON) def sayHello(self, name): return if __name__ == '__main__': try: print("Start the echo service") app = pyrestful.rest.RestService([EchoService]) app.listen(8080) tornado.ioloop.IOLoop.instance().start() except KeyboardInterrupt: print("\nStop the echo service")
2. Installation
pip install -U git+https://github.com/rancavil/tornado-rest.git
3. Use: a demo for CRUD
Here is the official Demo as a demonstration.
Goal: Design an Http server for the recording of student information. Need to provide Add, delete, modify, check Four major functions.
Two classes are predefined:
Define an Http Handler, inherited from pyrestful.rest.RestHandler :
class CustomerResource(pyrestful.rest.RestHandler): def initialize(self, database): self.database = database
3.1. Creating a new Customer
POST it is equivalent to INSERT.
Use the post method to pass in a new student information. The server receives the student information and stores it in the database.
Description of API interface:
POST: http://myserver.domain.com:8080/customer POST /customer HTTP/1.1 Host: myserver.domain.com params: * name_customer=Rodrigo * address_customer=Santiago
@post(_path="/customer", _types=[str,str], _produces=mediatypes.APPLICATION_JSON) def createCustomer(self, name_customer, address_customer): id_customer = self.database.insert(name_customer, address_customer) response = return response
- Use PostWoman Test API
- Use httplib Initiate a request
import http.client as httplib import urllib.parse as urllib params = urllib.urlencode() headers = conn = httplib.HTTPConnection("localhost:8080") conn.request('POST','/customer',params,headers) resp = conn.getresponse() data = resp.read() if resp.status == 200: json_data = json.loads(data.decode('utf-8')) print(json_data) else: print(data)
3.2. Read a Customer
GET it is equivalent to SELECT (READ).
Use the get method to obtain a student’s information in the database.
Description of API interface:
GET: http://myserver.domain.com:8080/customer/ GET /customer/1 HTTP/1.1
@get(_path="/customer/", _types=[int], _produces=mediatypes.APPLICATION_JSON) def getCustomer(self, id_customer): customer = self.database.find(id_customer) response = < 'id_customer' : customer.getId_Customer(), 'name_customer' : customer.getName_Customer(), 'address_customer': customer.getAddress_Customer() >return response
3.3. Update a Customer
PUT it is equivalent to UPDATE.
Description of API interface:
PUT: http://myserver.domain.com:8080/customer/ PUT /customer/1 HTTP/1.1 Host: myserver.domain.com params: * name_customer=Rodrigo * address_customer=Santiago
@put(_path="/customer/", _types=[int,str,str], _produces=mediatypes.APPLICATION_JSON) def updateCustomer(self, id_customer, name_customer, address_customer): updated = self.database.update(id_customer,name_customer,address_customer) response = < "updated_customer_id": id_customer, "success":updated >return response
3.4. Delete a Customer
Description of API interface:
DELETE: http://myserver.domain.com:8080/customer/ DELETE /customer/1 HTTP/1.1
@delete(_path="/customer/", _types=[int], _produces=mediatypes.APPLICATION_JSON) def deleteCustomer(self,id_customer): deleted = self.database.delete(id_customer) response = < "delete_customer_id": id_customer, "success":deleted >return response
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
A simple and useful Restful API for Tornado Web Server
rancavil/tornado-rest
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
pyRestful is an API to develop restful services with Tornado Web Server. Changes were made from the last version to improve the API.
Last version works with Python 2, 3.5 and 3.7.
Python version 2.7, 3.5+ are required.
Note: We recommend using Python 3.5+.
Unzip the file tornado-rest-master.zip
$ unzip tornado-rest-master.zip
Go to the directory and install.
$ cd tornado-rest-master $ python setup.py install
Or you can install it using.
$ pip install -U git+https://github.com/rancavil/tornado-rest.git
It was added «syntax sugar» to define services.
import tornado.ioloop import pyrestful.rest from pyrestful.rest import get,post class EchoService(pyrestful.rest.RestHandler): @get('/echo/') def sayHello(self, name): return class BookService(pyrestful.rest.RestHandler): @post('/book') def create_book(self,book): # do something. return 'Book created. ' class SomeService(pyrestful.rest.RestHandler): @post('/person',) # content-type (consumes and produces) will be application/json def create_person_json(self,book): # do something with book in format json return
If you want to see a complete example, you can go to demo folder and check person_service.py.
The API allows developing a CRUD (Create, Read, Update and Delete) over the resources. In this example the resource is Customer.
$ python demos/customer_service.py
Note: you can see customer_service.py is in demos folder.
Creating a new Customer:
POST: http://myserver.domain.com:8080/customer POST /customer HTTP/1.1 Host: myserver.domain.com customer_name=Rodrigo&customer_address=Santiago POST it is equivalent to INSERT.
Read a Customer:
GET: http://myserver.domain.com:8080/customer/ GET /customer/1 HTTP/1.1 GET it is equivalent to SELECT (READ).
Update a Customer:
PUT: http://myserver.domain.com:8080/customer/ PUT /customer/1 HTTP/1.1 Host: myserver.domain.com customer_name=Rodrigo&customer_address=Santiago PUT it is equivalent to UPDATE.
Delete a Customer:
DELETE: http://myserver.domain.com:8080/customer/ DELETE /customer/1 HTTP/1.1 DELETE it is equivalent to DELETE.
PyRestful implements the verbs get, post, put and delete.
This example implements an echo rest service (echo_service.py).
Write the next code and save echo_service.py file.
import tornado.ioloop import pyrestful.rest from pyrestful import mediatypes from pyrestful.rest import get class EchoService(pyrestful.rest.RestHandler): @get(_path="/echo/", _produces=mediatypes.APPLICATION_JSON) def sayHello(self, name): return if __name__ == '__main__': try: print("Start the echo service") app = pyrestful.rest.RestService([EchoService]) app.listen(8080) tornado.ioloop.IOLoop.instance().start() except KeyboardInterrupt: print("\nStop the echo service")
You can execute the service.
Then in a browser write the url.
http://localhost:8080/echo/john
You should see the following output in your browser.