Epython Lab
Link
click to show
click to show
While learning FastAPI, I came across another question: 𝐖𝐡𝐲 𝐝𝐨 𝐈 𝐧𝐞𝐞𝐝 𝐏𝐲𝐝𝐚𝐧𝐭𝐢𝐜 𝐰𝐡𝐞𝐧 𝐏𝐲𝐭𝐡𝐨𝐧 𝐚𝐥𝐫𝐞𝐚𝐝𝐲 𝐡𝐚𝐬 𝐭𝐲𝐩𝐞 𝐡𝐢𝐧𝐭𝐬?
For example, I can write:
𝑑𝑒𝑓 𝑐𝑟𝑒𝑎𝑡𝑒_𝑢𝑠𝑒𝑟(𝑛𝑎𝑚𝑒: 𝑠𝑡𝑟, 𝑎𝑔𝑒: 𝑖𝑛𝑡):
...
Python already tells me that name should be a string and age should be an integer.
So what does 𝐏𝐲𝐝𝐚𝐧𝐭𝐢c add?
The difference became clear when working with API request data.
An API receives data from outside the application, and I need more than just type hints. I need to validate that the data has the expected structure and values.
That’s where Pydantic becomes useful.
With FastAPI, I can define a model:
𝑐𝑙𝑎𝑠𝑠 𝑈𝑠𝑒𝑟𝐶𝑟𝑒𝑎𝑡𝑒(𝐵𝑎𝑠𝑒𝑀𝑜𝑑𝑒𝑙):
𝑛𝑎𝑚𝑒: 𝑠𝑡𝑟 𝑎𝑔𝑒: 𝑖𝑛𝑡
FastAPI can then use that model to validate incoming request data automatically.
So my takeaway is:
𝐏𝐲𝐭𝐡𝐨𝐧 𝐭𝐲𝐩𝐞 𝐡𝐢𝐧𝐭𝐬 𝐝𝐞𝐬𝐜𝐫𝐢𝐛𝐞 𝐰𝐡𝐚𝐭 𝐈 𝐞𝐱𝐩𝐞𝐜𝐭.
𝐏𝐲𝐝𝐚𝐧𝐭𝐢𝐜 𝐡𝐞𝐥𝐩𝐬 𝐯𝐚𝐥𝐢𝐝𝐚𝐭𝐞 𝐰𝐡𝐚𝐭 𝐈 𝐚𝐜𝐭𝐮𝐚𝐥𝐥𝐲 𝐫𝐞𝐜𝐞𝐢𝐯𝐞.
This is another small concept that became much clearer once I started building a real FastAPI application.
𝐖𝐡𝐚𝐭 𝐰𝐚𝐬 𝐲𝐨𝐮𝐫 𝐟𝐢𝐫𝐬𝐭 𝐢𝐦𝐩𝐫𝐞𝐬𝐬𝐢𝐨𝐧 𝐨𝐟 𝐏𝐲𝐝𝐚𝐧𝐭𝐢𝐜 𝐰𝐡𝐞𝐧 𝐲𝐨𝐮 𝐬𝐭𝐚𝐫𝐭𝐞𝐝 𝐮𝐬𝐢𝐧𝐠 𝐅𝐚𝐬𝐭𝐀𝐏𝐈?
🔗 𝐆𝐢𝐭𝐇𝐮𝐛: https://github.com/epythonlab2/ai-document-api
🎥 𝐅𝐚𝐬𝐭𝐀𝐏𝐈 𝐜𝐨𝐮𝐫𝐬𝐞: https://www.youtube.com/watch?v=0SLLG2Z_Htw&list=PLQNCas8_eikM
89 ·