FastAPI - IDE Support

The Type Hinting feature of Python is most effectively used in almost all IDEs (Integrated Development Environments) such as PyCharm and VS Code to provide dynamic autocomplete features.

Let us see how VS Code uses the type hints to provide autocomplete suggestions while writing a code. In the example below, a function named as sayhello with name as an argument has been defined. The function returns a string by concatenating “Hello” to the name parameter by adding a space in between. Additionally, it is required to ensure that the first letter of the name be in upper case.

Python’s str class has a capitalize() method for the purpose, but if one doesn’t remember it while typing the code, one has to search for it elsewhere. If you give a dot after name, you expect the list of attributes but nothing is shown because Python doesn’t know what will be the runtime type of name variable.

FastAPI IDE Support

Here, type hint comes handy. Include str as the type of name in the function definition. Now when you press dot (.) after name, a drop down list of all string methods appears, from which the required method (in this case capitalize()) can be picked.

FastAPI IDE Support

It is also possible to use type hints with a user defined class. In the following example a rectangle class is defined with type hints for arguments to the __init__() constructor.

class rectangle:
   def __init__(self, w:int, h:int) ->None:

Following is a function that uses an object of above rectangle class as an argument. The type hint used in the declaration is the name of the class.

def area(r:rectangle)->int:
   return r.width*r.height
print ("area = ", area(r1))

In this case also, the IDE editor provides autocomplete support prompting list of the instance attributes. Following is a screenshot of PyCharm editor.

FastAPI IDE Support

FastAPI makes extensive use of the type hints. This feature is found everywhere, such as path parameters, query parameters, headers, bodies, dependencies, etc. as well as validating the data from the incoming request. The OpenAPI document generation also uses type hints.

Kickstart Your Career

Get certified by completing the course

Get Started