Home FastAPI (2) Type Hint(English)
Post
Cancel

FastAPI (2) Type Hint(English)

Type Hint

Why are Type Hints important? Because Python is a dynamically typed language, meaning you don’t need to specify the type of parameters when writing a function. The type of the parameters is determined dynamically at runtime. This feature allows for dynamic type checking and late binding, offering greater flexibility. However, the downside is that it often leads to runtime exceptions if not carefully managed.

A simple example on tutorialspoint can explain this concept.

Let’s define a division function that accepts either double or int types. In a statically typed language like C++, the same function would throw an error at compile time.

Desktop View

But if you pass an incorrect type that can’t be operated on, such as a string (which lacks a division operator), it will result in a runtime exception.

Desktop View

Python 3.5 and above supports Type Hints, which provide type hints when calling a function during coding. However, if you insist on passing the wrong type of parameter, it won’t stop you. Unlike statically typed languages, you won’t catch these errors early and be forced to fix them before the code can compile.

Using Type Hints in FastAPI

Let’s look at some code! We define an API that must be called with /test2/{name}/{number}. Here, name must be of type str, and number must be of type int.

1
2
3
4
5
6
7
import uvicorn
from fastapi import FastAPI, Path
app = FastAPI()

@app.get("/test2/{name}/{number}")
async def test2(name:str, number:int):
    return {"name":name, "number":number}

Correct request

http://127.0.0.1:8000/test2/kobe/24

Desktop View

Incorrect request

http://127.0.0.1:8000/test2/kobe/24.5

The API will return the error reason directly.

Desktop View

Conclusion

Using Type Hints in FastAPI allows for direct handling of parameter errors without needing to include try-catch error checking and handling in the function. This is very convenient!

BTW, tutorialspoint is one of my favorite tutorial sites. It is concise and easy to read. If you want to learn a language or skill, you can check it out there.

☝ツ☝

This post is licensed under CC BY 4.0 by the author.

👈 ツ 👍