Interactive Testing: Introduction

Get to know the learning objectives of this chapter.

Introduction

In this chapter, we will review interactive testing with HTTPie and introduce pytest, which is a great way to create Python tests. We’ll also address the challenges that come up with testing a Flask application.

How to use HTTPie

In Server-Side API Creation with Flask , we look at how to use HTTPie to interact with our web API.

$ http POST 0.0.0.0:3000/my-api number=1729 description="First taxi-cab number"

This uses the POST method on the local server at the route /my-api with the JSON payload:

{
   "number" : 1729,
   "description" : "First taxi-cab number"
}

The response is headers, then a single number, which is the ID of the new record. An alternative approach would be to return an object like {"newId":4} instead of just the number 4 - this additional information makes it easier to use and provides context to the number returned. We’ve chosen to use the number to emphasize that JSON data is not required to be an object but can also be a string, number, null, boolean, or list.

In the example, we specify data fields using the = sign. By default, the values are viewed as strings. Use := instead of = to submit a value as a number, as shown here for the number field.

$ http POST 0.0.0.0:3000/my-api number:=1729 description="First taxi-cab number"

Because the Flask route expects an integer, it will attempt to convert strings to integers first, so the input can be either a string or an integer and produce the same effect. HTTPie also makes it easy to specify HTTP headers using a colon, such as X-API-Token:e034a8c, which can be useful for testing authentication methods. HTTPie can treat the key-value pairs as form input if we include the --form or -f option.

$ http --form POST 0.0.0.0:3000/my-api number=1105 description="First Carmichael number"

Get hands-on with 1200+ tech skills courses.