Codementor Events

Building Restful API with Flask, Postman & PyTest - Part 2 (Read Time: 10 Mins)

Published Jun 21, 2019
Building Restful API with Flask, Postman & PyTest - Part 2 (Read Time: 10 Mins)

Today we shall cover the creation of mock endpoints in Postman. To help in the designing & prototyping of API endpoints for the expense manager project using Flask and pytest in part 3.

For those that are new to this series, you can go to part 1 to understand the explanation of tools and libraries used for this series to create API endpoints in Flask.

You are encouraged to jump between each tutorial sections. I had included this postman collection to get you started to play around with mock endpoints.

Project Specification

The expenses manager has to have the following features for the API endpoints:

  • Display the balance
  • Adjusting balance
  • Display list of transactions
  • Display an individual transactions detail
  • Add transaction
  • Update a specific transaction detail
  • Remove a transaction

Why Create Mock APIs Instead of Building the API?

The reason for it is to help in the prototyping process of developing the endpoints.

By creating prototypes, you gain the perspective on how to create the endpoints and see on how it will look like in the final product.

Using your Prototype to Gain Understanding & Common Ground

With the use of the prototypes, it allows you to communicate your understanding and get feedback to make changes before you start in developing the actual product.

Breaking Dependence of Front-end & Back-end

Through the creation of mock endpoints in postman , you break the inter-dependency issue that you might encounter with the front-end developers regarding on APIs.

There is always a problem in having the API endpoint to be operating 24/7 to test out your front-end's UI or the API you had built when you're moving at a fast pace.

Fortunately, with the creation of mock endpoints in Postman, it had made it easier to collaborate at a much faster pace.

Creating a Postman Collection

Before you start on creating mock endpoint you have to sign up for a postman account.

Once had created your new account, download the postman app in your os. Create a new postman collection called Expenses Manager. A postman collection is a place to store your API request in postman.

Create a new Postman Collection

Naming the Postman Collection

Creating a Mock Server In Postman

Now in your newly created Postman collection, click on the ">" icon and select the mocks tab.

There will be a button that says create a mock server click on that button to create a mock server as shown in the picture below.

Selecting Create Mock Server button

Select the default settings and click create button as shown below.

Select Default Settings for Mock Server

With a mock server URL for your postman collection, you need to enable the Expenses Manager environment to use the mock server.

Created Postman Mock Server

Enabling the Postman Environment

To enable the Postman, go to your top right corner just beside the icon with an eye.

Click a dropdown box with the name No Environment. Select Expenses Manager environment.

Select Expenses Manager Environment

Select eye icon, it will show you the mock server's link under the local environment variable called url.

The variable allows you to create API points without the need to replace the URL of each request which saves you time.

Select Expenses Manager Environment

Creating A New Request

Now we shall proceed in setting your first request in postman. Select your "Expenses Manager" collection and click on the "..." button that is at the bottom of the arrow button.

Once you had click on the button, a list of options is displayed then click on Add Request as shown in the picture below.

Create new request

From there enter the name of your new request called Get List of Transactions and save it to the expenses manager collection.

Save new request

display new request

Editing the Description of a Request

Let's add descriptions to the request, click on arrow icon and then edit icon as shown below.

The description will become part of automatically created documentation. Therefore it is useful to add it in to explain what does the API do.

API Description: Get the list of transactions in the expenses manager

Create Description for API Request

List of API Requests in Postman

In RESTful API, there are a bunch of HTTP methods for different use cases.

You could get the list of methods founded by clicking on the arrow button of the GET method in your request.

List of Request Methods

Types of API Request Methods

Here are the HTTP methods that you will use for this expanses manager project or future APIs that you will be creating.

They follow a similar structure to the CRUD function of the typical database.

They are as follows:

  • GET - Displays a list of records or specific record.
  • POST - it creates a record.
  • PUT - Updates an existing record or multiple records in the API. Besides that, it can create new records thus you need to catch any PUT operations that does not update existing records.
  • DELETE - Deletes existing records.

Edit Get List of Transactions Request

Now go to List of Transactions Request and enter the following URL.

Enter URL of the request

The {{url}} represents the mock server URL.

Duplicate the API Requests

Duplicate the following request shown in the picture.

  • Get an Individual Transaction - GET
  • Create a New Transaction - POST
  • Update an Individual Transaction - PUT
  • Delete an Individual Transaction - DELETE
  • Get Current Balance - GET
  • Update Current Balance - PUT

List of requests

Creating an Example Response

An example response is a mock response whenever you send an HTTP request.

Select the Get List of Transactions request and add a new example response.

Crate Example Response

Once you had created a new example, you will be shown the example response message as shown below.

Blank Example Response

Replace the name with Success Response and enter the body of the response shown below.

{
    "balance": 200,
    "transactions": [
        {
            "id": 1,
            "amount": "60",
            "description": "New jeans",
            "type": "expense",
            "inital_balance": 300,
            "current_balance": 240,
            "time": "2019-01-12 09:00:00"
        },
        {
            "id": 2,
            "amount": "40",
            "description": "Lunch at a restaurant",
            "type": "expense",
            "inital_balance": 240,
            "current_balance": 200,
            "time": "2019-01-12 12:00:00"
        },
        {
            "id": 3,
            "amount": "10",
            "description": "Tips",
            "type": "income",
            "inital_balance": 200,
            "current_balance": 210,
            "time": "2019-01-12 16:00:00"
        },
        {
            "id": 4,
            "amount": "10",
            "description": "Weekly bus pass",
            "type": "expense",
            "inital_balance": 210,
            "current_balance": 200,
            "time": "2019-01-12 18:00:00"
        }
    ]
}

Replace Example Response

Add Status Code

The status code is used to identify that an HTTP request to a server is successful. The most common type of HTTP status code is 404 which displays when there is no webpage for a website.

At the status dropdown box, you can select the status code for the example response which in this case is 200.

List of HTTP Status Code

Overview of the Example Response

Now when you click on the send button on your Get List of Transactions request.

Receiving Response by Sending HTTP Request

You will be displayed the example response that you had created earlier.

Congrats Gif

Congratulations , you had created your first mock endpoint!!!

Now please create the remaining mock endpoints for the expenses manager project and test it out on your own.

I had included the Postman collection for the Expanses Manager. If your feeling lazy to play around with the mock endpoints, don't worry I won't tell anyone.

Expanses Manager Postman Collection

Conclusion

I hope that with your new founded skills in creating mock endpoints in postman. It can help you greatly in reducing the dependency between your front-end and the APIs you build.

Lastly, did you remember that you added the description of your API request?

Well, all Postman collections come with API documentation page that displays all your API requests and example responses for each API.

Having great API documentation is one of the keys to adopting APIs be it for internal, external or public use cases.

So, postman, have you covered in creating these documentations without spending any of your time writing it.


Page 2

Published: January 06, 2019

For the first part of the 3 part series of the building Restful API with Flask, Postman and PyTest.

I will be covering the explanation of the libraries and tools used to create a expenses manager project based upon Testing Python Applications with Pytest so that you will understand why you might use these tools or libraries as part of your development process to develop APIs in Flask.

Whereas in part 2 of the series, I will cover the API design of the expenses manager and mocking API endpoints in Postman.

Finally, for part 3 we will be implementing the API in flask with test cases built using PyTest.

Journey from a Django Developer to an API Developer

When I first started to become a Django developer, I learnt the basics on how to build a basic website with Django , SQL Database and JQuery.

As I grow in experience, I realised the importance of building single page web apps by using front-end frameworks with Django as backend.

I learnt to combine my understanding of front-end framework from Udacity with Django Rest framework to develop APIs for the front-end to consume for my backend during my work.

Building APIs using Flask

Flask is another python based web framework that is considered the go to framework for developing Restful APIs.

I had come across multiple articles or sources in freeCodeCamp due to its flexibility & simplicity to create APIs without much effort.

Coming from experience using Django Rest Framework , I was quite sceptical of it when I first started to use it.

With time flask wins me over but due to flask's flexibility, it can be painful in learning.

Due to the reason that there is no one specific way in building an API compared to Django Rest Framework.

Mocking & Testing Using Postman

While building APIs, I started to use tools that allow me to test my API at a much faster pace.

One of these tools is Postman, which I used it as a testing tool and API documentation for my front-end developer initially.

But I found out later that you can break the interdependence problem of front-end and backend through using the Postman's mock server feature.

Breaking API Dependence Workflow of Frontend & Backend.

With Postman's mock server, a front-end developer can focus on integrating mock endpoints without relying on the backend.

Whereas for the backend developer, they could focus on providing the front-end with a working endpoint and swap it around when it has completed. Further reducing the time to ship for the development team.

Creating Test Cases with PyTest

PyTest is my goto testing framework in python as it is easy to learn and has lesser boilerplate code compared to the default installed unittest library.

Which follows the JUnit style of implementation which could be intimating when you first started to use.

Conclusion

I hope the first part of the series explains the rationale on using tools or libraries like Postman and Pytest can help in speeding up the development process.

Please stay tuned for part 2 and part 3 of the series to teach you on how to create mock endpoints and implement it in Flask with test cases in Pytest.

Subscribe to a weekly newsletter, fresh from the oven at one byte at a time

Discover and read more posts from Max Ong Zong Bao
get started
post commentsBe the first to share your opinion
Show more replies