Rest API in my experience

Post on 27-Aug-2014

525 views 8 download

Tags:

description

Sharing my experience with REST API over the years in PyCon Dhaka 2014

Transcript of Rest API in my experience

RESTful APITamim Shahriar Subeen

Mukto Software Ltd.

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'

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

if request.method == 'GET':

...

if request.method == 'POST':

...

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

ResponseStatus Code, Content

Searching ...

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

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!

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.

REST API Testing Methods

● Browser Addons● CURL● Write Your Own Code

○ requests modulerequests.get

requests.put

requests.post

requests.delete

Use a Framework

unittestUnit testing framework in Python

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()