Essential FastAPI Practices Every Developer Should Embrace
Written on
Chapter 1: The Shift from Student to Professional
As a student, my approach to coding was often rushed; if the code worked, I left it as is. This mindset led to the creation of poor-quality code—difficult to read, confusing, and not reusable. After graduating and starting my career with enterprise-level Python applications, I encountered numerous pull requests that were rejected due to my disregard for best practices. While it was frustrating, it helped me understand the importance of writing maintainable code.
Here, I outline five essential FastAPI concepts and practices that we must start taking seriously as we transition into the professional realm.
Section 1.1: Prioritizing Code Reusability
During my student days, I often neglected the idea of reusability:
def func1():
# step A
# step B
# step C
# step D
def func2():
# step A
# step B
# step C
# step E
def func3():
# step A
# step B
# step C
# step F
In the example above, steps A, B, and C are repeated across three functions. This redundancy not only makes the code less reusable but also complicates future updates.
A better approach in enterprise applications could involve creating a utility function:
def util_func():
# step A
# step B
# step C
def func1():
util_func()
# step D
def func2():
util_func()
# step E
def func3():
util_func()
# step F
By consolidating common steps into a single function, we enhance reusability and maintainability.
Section 1.2: Enhancing Code Readability
As a novice, I often used single-letter variable names like x, a, and b. However, after gaining experience, I've learned the value of descriptive naming, such as person_id and person_name.
I also overlooked type hinting, despite knowing it existed. Here’s an example without type hints:
def do_something(mylist, a):
return [i + a for i in mylist]
And with type hints:
from typing import List
def do_something(mylist: List[int], a: int) -> List[int]:
return [i + a for i in mylist]
Type hints improve code readability, making it easier for others to understand the expected types and return values.
Section 1.3: Implementing Authorization
In my early projects, I created APIs in FastAPI that were open to everyone. However, when developing enterprise applications, security is paramount. Each user should have defined roles that dictate their access to various endpoints.
Generally, role data is stored in a database, allowing for tailored access control based on user roles.
Section 1.4: Data Access Control
Beyond basic authorization, defining which data subsets users can access adds another layer of security. For example:
- Admins can access all data.
- Privileged users may access 80% of the data.
- Regular users can only interact with their own data.
This approach varies by application, emphasizing the necessity for tailored solutions.
Section 1.5: Utilizing Response Models in FastAPI
As a student, I often wrote minimal code to achieve functionality:
@app.get('/test')
def test(id):
return get_one(id)
Without a response model, understanding the output requires additional effort. To aid other developers, we can define a response model:
from pydantic import BaseModel
class Person(BaseModel):
name: str
age: int
gender: str
@app.get('/test', response_model=Person)
def test(id):
return get_one(id)
This approach clarifies what the API is expected to return, which can also be viewed in the Swagger UI.
Conclusion
While FastAPI offers a wealth of features, this list highlights five fundamental practices that new developers should adopt for cleaner, more maintainable code.
If you wish to support me as a creator, please engage with this content through comments and shares. Your support is invaluable!
The first video titled "5 Things about FastAPI I Wish We Had Known Beforehand" offers insights into common pitfalls and best practices that developers should consider.
The second video, "Why You NEED To Learn FastAPI | Hands On Project," emphasizes the importance of mastering FastAPI through practical examples and projects.
Thank you for reading! Your interactions help me continue creating valuable content.