First start without JSON to make sure your code works. Then update your code to work with JSON. Here is a working example of your calculator.
This example shows it without JSON. Example with JSON is below.
Working example without JSON
Server side in cherrypy (server1.py
):
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import cherrypy
def add(a, b):
return a + b
class Calculator:
exposed = True
def POST(self, a, b):
result = add(int(a), int(b))
return 'result is {}'.format(result)
if __name__=='__main__':
app_config = {
'/': {'request.dispatch':cherrypy.dispatch.MethodDispatcher()}
}
cherrypy.tree.mount(Calculator(), '/api/add', config=app_config)
cherrypy.config.update({
'server.socket_host' : '127.0.0.1',
'server.socket_port' : 9090,
})
cherrypy.engine.start()
cherrypy.engine.block()
Run the cherrypy server as a separate process. Open another terminal window, command line or whatever you use and use this API client to send a request. Name it client1.py
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import requests
url = 'http://127.0.0.1:9090/api/add'
data = {
'a': 12,
'b': 13
}
response = requests.request('POST', url, data=data)
print(response.text)
If you send the request, you get this response:
$ python send.py
result is 25
Working example with JSON
CherryPy server side (server2.py
):
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import cherrypy
import json
def add(a, b):
return a + b
class Calculator:
exposed = True
@cherrypy.tools.json_in()
def POST(self):
input_json = cherrypy.request.json
result = add(input_json['a'], input_json['b'])
return 'result is {}'.format(result)
if __name__=='__main__':
app_config = {
'/': {'request.dispatch':cherrypy.dispatch.MethodDispatcher()}
}
cherrypy.tree.mount(Calculator(), '/api/add', config=app_config)
cherrypy.config.update({
'server.socket_host' : '127.0.0.1',
'server.socket_port' : 9090,
})
cherrypy.engine.start()
cherrypy.engine.block()
API client, name it client2.py
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import requests
url = 'http://127.0.0.1:9090/api/add'
data = {
'a': 12,
'b': 13
}
headers = {'content-type': 'application/json'}
# Note that there is json=data not data=data.
# This automatically converts input data to JSON
r = requests.request('POST', url, json=data, headers=headers)
print(r.status_code)
print(r.text)