REST api in Python 3.x (Part 2)

In this post we will learn how to develop RESTapi in Python 3.x with REST conventions.

In the first edition we learnt about REST and implementation of RESTful services in Python 3.x and Flask. We also created multiple URLs for different GET requests .

In this tutorial we will talk about –

  1. POSTMAN (Testing client for RESTapi’s).
  2. POST, PUT and DELETE methods.
  3. JSON format requests and responses and why these are necessary.

Let’s get started with our RESTapi development on a proper note.

POSTMAN

Using a web browser to test a web service isn’t the best idea since web browsers cannot easily generate all types of HTTP requests. Remember that POST, PUT and DELETE requests can only be sent from html forms or similar. Therefore, we will be using POSTMAN as our client to test our RESTapi. We can also use curl for the same purpose, but Postman has many more features such as request/response validation, collection testing, etc.

postman

POSTMAN is a complete toolchain for APIs developers and it makes working with APIs faster and easier. To use Postman, you can download it from here.

POST, PUT and DELETE Methods

Okay, now a simple question would be, when we can use GET method, why to use these different methods too? Where to use them and in what use case?

In REST conventions, we always talk about a “resource” as a noun. So to keep the standards in a uniform REST convention, following these HTTP verbs and using them in correct way will not only make your system follow the norm but also to understand it better. The basic HTTP verbs are POST, GET, PUT, PATCH, DELETE. These correspond to CREATE, READ, UPDATE, DELETE respectively in a CRUD system. We will go into deep understanding below.

A resource is any abstract entity in a system which can be accessed by a URI. For example, url – http://localhost:5000/task depicts the “task” resource. A GET request on this url will mean “read/get tasks”, POST request would mean “create a task”, PUT/PATCH request would mean “update the tasks” and DELETE request would mean “delete the tasks”. Remember, tasks is used as a plural term when we say “read/update/delete tasks” but used as singular term when using POST or create “a” task.

POST method –

This method is mostly used in CREATE operations. So tasks like making a new object, inserting new tables in a database, creating a new task or any type of creating a resource comes under POST request. A POST request is generally used to create a single entity or a resource in REST standards. Some examples –

  • /task – Create a new task.
  • /order – Create a new order.
  • /app – Create a new app.

POST method API’s should normally return an ID assigned to the new object created. This ID will be now used to access this particular resource again. We also send back the necessary response code if the resource has been successfully created. By default, Flask will send a 200 response code (OK) but in POST a 201 needs to be sent (Created). The list of status codes can be found here.

GET method –

This method is mostly used in viewing or retrieving data of resources or a particular resource. Note the type of URL patterns below –

  • /task – Get a list of tasks present.
  • /task/{task_id} – Get the details of the task having ID as task_id.
  • /order – Get a list of orders present.
  • /order/{order_id} – Get the details of order having ID as order_id.

Obviously, these task_id / order_id are just names given, you can use any naming convention you want. NOTE the usage of singular resource in the URL, as the type and verb will automatically define the usage of this URL, plural words/resources should not be used.

PUT/PATCH method –

This method works in the same way as GET methods but is used to update the resource. The main difference between PUT and PATCH request is the norm to be followed inside them. While PUT request generally creates a copy object of the resource and then updates the whole resource with the new object, PATCH request just updates the original resource in-place. Examples –

  • /task- Update a batch of tasks.
  • /task/{task_id} – Update the task having ID as {task_id}
  • /order – Update a batch of orders present.
  • /order/{order_id} – Update the details of order having ID as order_id.

DELETE method –

This method is used obviously to delete the resources. It also works in similar fashion to GET and PUT requests. Some examples –

  • /task- Delete a batch of tasks.
  • /task/{task_id} – Delete the task having ID as {task_id}
  • /order – Delete a batch of orders present.
  • /order/{order_id} – Delete the details of order having ID as order_id.

While some of you must argue that in real systems, we do not delete the actual data/resource but update its “active” flag to False or similar ways. Then why not use PUT/PATCH method for deleting a resource?

Well, what we do inside an API endpoint is up to us, but the overall system must behave as per REST guidelines. Therefore, even if we are updating a flag value, for the actual users/clients, the resource has been DELETED (however way) and hence, must mean that the API used for doing this must have the DELETE verb associated with it.

IMPLEMENTATION

Let’s create some sample URL’s for this. We will make a makeshift database (python list) just to showcase the API endpoints created. Update the code of “blog.py” with this.

Screenshot 2019-02-17 at 2.15.35 PMScreenshot 2019-02-17 at 2.15.45 PM

So now, we have created a view (a function that takes in a request and return response is known as a view) that will create an order, list all the orders, update all the orders, delete all the orders. Run the code by the line – python blog.py
Now open Postman and go to the url localhost:5000/order, select body, raw data, JSON type. Enter the body of the request you have to send as shown below. When you press Send, the following response should be shown below.

Screenshot 2019-02-17 at 2.18.54 PM

This means you have successfully created an order having name “ord_1” and quantity as 10. Now change the verb from POST to GET and see what happens.!! You get the following output.!

Screenshot 2019-02-17 at 2.20.27 PM.png

Why use jsonify()

RESTapi means that this script, when deployed, could be used to request and receive data from ANY platform. By default it returns HTTP format data when using syntax like return “Hello World”. This HTTP data cannot be handled explicitly in many platforms like Android, JAVA applications, etc. Therefore, we send the data encoded as JSON to make it platform independent. We do this by importing and using the method jsonify() in the Flask package when returning the response to the client.

Great..!! Now go ahead, play with the types of verb discussed above and try to see what happens!

The proper naming feature is now available in this post.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Powered by WordPress.com.

Up ↑

%d bloggers like this: