Download - Rest API in my experience

Transcript
Page 1: Rest API in my experience

RESTful APITamim Shahriar Subeen

Mukto Software Ltd.

Page 2: Rest API in my experience

In Ancient Dayshttp://example.com/?command=command_name&param1=p&param2=q...

command = form['command']

if command == 'get_list':

...

elif command == 'create_list':

param1 = form['param1']

param2 = form['param2']

...

elif command == 'update_list':

...

elif command == 'delete_list':

...

else:

print 'Unknown Command'

Page 3: Rest API in my experience

Framework!http://example.com/list/?

if request.method == 'GET':

...

if request.method == 'POST':

...

Page 4: Rest API in my experience

Time passes on ...HTTP MethodsGET : Read A ResourcePOST : Create a ResourcePUT : Update a ResourceDELETE : Delete a Resource

ResponseStatus Code, Content

Page 5: Rest API in my experience

Searching ...

Page 6: Rest API in my experience

Flask-RESTfulclass Todo(Resource):

def get(self, todo_id):

abort_if_todo_doesnt_exist(todo_id)

return TODOS[todo_id]

def delete(self, todo_id):

abort_if_todo_doesnt_exist(todo_id)

del TODOS[todo_id]

return '', 204

def put(self, todo_id):

args = parser.parse_args()

task = {'task': args['task']}

TODOS[todo_id] = task

return task, 201

Page 7: Rest API in my experience

Test Your REST API

Write tests for successful failure!GET http://example.com/todos/It should successfully return 404 status code

DELETE http://example.com/todos/-1It should successfully return 404 status code

Check the status code and also the error message!

Page 8: Rest API in my experience

Test Your REST API

Write tests for successful success!GET http://example.com/todos/1It should successfully return the to_do item with task id 1 and 200 status code

DELETE http://example.com/todos/1It should successfully delete the task with id 1 return 204 status code

Check the status code first, then validate the response data.

Page 9: Rest API in my experience

REST API Testing Methods

● Browser Addons● CURL● Write Your Own Code

○ requests modulerequests.get

requests.put

requests.post

requests.delete

Page 10: Rest API in my experience

Use a Framework

unittestUnit testing framework in Python

Page 11: Rest API in my experience

Code in Actionimport requests

import unittest

class TestShopolotApi(unittest.TestCase):

def setUp(self):

print " in setup "

def tearDown(self):

print " in teardown "

def test_login_wrong(self):

print "testing login 1"

url = 'http://example.com/' + 'login'

data = {'email': email, 'password': password_hash}

r = requests.post(url, data)

self.assertEqual(r.status_code, 400)

if __name__ == '__main__':

unittest.main()

Page 12: Rest API in my experience