Data validation

There is one nasty problem with our current implementation: it is easy to misspell a complaint type—and the API won't let us know of any issue; instead, it will pass it to the model, which will return a null value because it couldn't find a corresponding complaint type.

To make behavior more transparent and easy to work with and to not spend any computations on the invalid requests, we'll need to validate all inputs. In order to do that, let's pre-define the complaint types we have, using the Enum library; mixing with str allows FastAPI to incorporate it into the schema, as follows:

class ComplaintType(str, Enum):
other = "other"
commercial = "commercial"
park = "park"
residential = "residential"
street = "street"
vehicle = "vehicle"
worship = "worship"
truck = "truck"

Now, we modify our app request function by adding ComplaintType as our type hint. We added a simple formatting logic; in a real app, it would make sense to simplify the complaint type in the data so that the app logic will be cleaner (and a tiny bit faster):

@app.get('/complaints/noise/{complaint_type}/time')
def complaints(complaint_type: ComplaintType):
if complaint_type == ComplaintType.other:
ct = "noise"
else:
ct = f"noise - {complaint_type.value}"

return {
"complaint_type": complaint_type,
"ct": ct,
"expected_time": model.predict(ct),
}

We didn't really change much in our code, but the class allows FastAPI to know which values are valid and which ones are not; now, instead of returning null, our application will raise a validation error, notifying us that our complaint type is invalid. Here is how it looks in practice:

>>> curl -X GET http://127.0.0.1:8000/complaints/noise/wrong/time -H "accept: application/json"

{"detail":[{"loc":["path","complaint_type"],"msg":"value is not a valid enumeration member","type":"type_error.enum"}]}

And the best part is that this expectation is reflected in the documentation! Our OpenAPI page now has a drop-down menu with all of the types our endpoint supports:

So, this is how our API finally looks. Next, let's move on to sending data with POST.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset