Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

Monday, 22 December 2025

FastAPI Dependency Injection Explained with Examples

Dependency Injection (DI) is one of the most powerful features of FastAPI, yet it’s also one of the most confusing topics for beginners.

If you are coming from Spring Boot, you may think:

“Where is @Autowired in FastAPI?”

In this post, we’ll explain FastAPI Dependency Injection in simple terms, with real-world examples and best practices.


What Is Dependency Injection?

Dependency Injection means:

Passing required objects (dependencies) into a function instead of creating them inside the function.

Why it matters

  • Cleaner code

  • Better reusability

  • Easier testing

  • Loose coupling


Dependency Injection in FastAPI

FastAPI provides dependency injection using the Depends() function.

It allows you to:

  • Inject database connections

  • Inject authentication logic

  • Inject services

  • Share common logic across APIs


Basic Dependency Injection Example

Simple dependency function

from fastapi import Depends def get_message(): return "Hello from dependency"

Using it in an API

from fastapi import FastAPI, Depends app = FastAPI() @app.get("/hello") def hello(message: str = Depends(get_message)): return {"message": message}

📌 FastAPI automatically:

  • Calls get_message()

  • Injects the returned value

  • Manages execution order


Dependency Injection vs Normal Function Call

❌ Without DI:

@app.get("/users") def get_users(): db = create_db_connection() return db.fetch_users()

✅ With DI:

def get_db(): return create_db_connection() @app.get("/users") def get_users(db = Depends(get_db)): return db.fetch_users()

✔ Cleaner
✔ Reusable
✔ Test-friendly


Real-World Example: Database Dependency

Database session dependency

def get_db(): db = DBSession() try: yield db finally: db.close()

Injecting DB into API

@app.get("/users") def get_users(db = Depends(get_db)): return db.get_all_users()

📌 FastAPI handles:

  • Opening the DB

  • Closing the DB

  • Exception safety


Dependency Injection for Authentication

Auth dependency

def get_current_user(token: str = Depends(oauth2_scheme)): return decode_jwt(token)

Protected API

@app.get("/profile") def profile(user = Depends(get_current_user)): return user

✔ Auth logic is reusable
✔ APIs stay clean


Dependency Injection for Services (Spring Boot Style)

Service class

class UserService: def get_users(self): return ["Alice", "Bob"]

Dependency provider

def get_user_service(): return UserService()

API using service

@app.get("/users") def users(service: UserService = Depends(get_user_service)): return service.get_users()

📌 This is similar to:

@Autowired UserService userService;

Dependency Injection with Parameters

Dependencies can also accept parameters:

def common_params(limit: int = 10, offset: int = 0): return {"limit": limit, "offset": offset} @app.get("/items") def get_items(params = Depends(common_params)): return params

Great for:

  • Pagination

  • Filters

  • Query parameters


Nested Dependencies

Dependencies can depend on other dependencies:

def get_db(): ... def get_user(db = Depends(get_db)): ...

FastAPI resolves them automatically.


Dependency Injection for Testing (Huge Benefit)

Override dependency in tests

app.dependency_overrides[get_db] = get_test_db

✔ No real DB
✔ Faster tests
✔ Cleaner test setup


Common Use Cases for Dependency Injection in FastAPI

✅ Database sessions
✅ Authentication & authorization
✅ API keys
✅ Logging
✅ Configuration
✅ Feature flags


Common Mistakes to Avoid

❌ Creating DB connections inside endpoints
❌ Writing auth logic repeatedly
❌ Mixing business logic in controllers
❌ Not using DI for shared logic


FastAPI DI vs Spring Boot DI

FeatureFastAPISpring Boot
DI StyleFunction-basedAnnotation-based
Learning curveEasyMedium
FlexibilityVery highStructured
BoilerplateLowHigh

FastAPI DI is lighter, while Spring DI is more structured.


Best Practices

✔ Keep dependencies small
✔ Use DI for cross-cutting concerns
✔ Avoid heavy logic in endpoints
✔ Use DI for better testing
✔ Name dependencies clearly


Final Thoughts

FastAPI’s Dependency Injection system is:

  • Simple

  • Powerful

  • Pythonic

  • Production-ready

Once you master Depends(), your FastAPI code becomes:

  • Cleaner

  • More maintainable

  • Easier to scale


Suggested Next Reads

  • FastAPI Project Structure Best Practices

  • FastAPI Microservices Setup

  • FastAPI Authentication with JWT

  • FastAPI Interview Questions

Saturday, 17 June 2023

How do you learn Python from basic until you become a programmer?

Here are some tips on how to learn Python from basic until you become a programmer:

  1. Set realistic goals. Don't expect to become a master programmer overnight. It takes time and effort to learn a new programming language. Start by setting small, achievable goals for yourself. For example, you could start by learning the basics of Python, such as variables, data types, and operators. Once you have mastered the basics, you can move on to more advanced topics, such as functions, classes, and modules.
  2. Find a good learning resource. There are many great resources available to help you learn Python. Books, online tutorials, and coding bootcamps can all be helpful. It's important to find a resource that fits your learning style and budget.
  3. Practice regularly. The best way to learn Python is to practice regularly. Try to set aside some time each day to work on your Python skills. You can practice by writing your own code, working on coding challenges, or contributing to open source projects.
  4. Don't be afraid to ask for help. If you get stuck, don't be afraid to ask for help. There are many online forums and communities where you can get help from other Python developers. You can also hire a Python tutor or take a coding bootcamp.
  5. Be patient and persistent. Learning Python takes time and effort. Don't get discouraged if you don't understand something right away. Keep practicing and you will eventually get the hang of it.

Here are some additional tips for becoming a programmer:

  • Build projects. One of the best ways to learn Python is to build projects. This will help you to apply what you have learned and to develop your problem-solving skills.
  • Contribute to open source projects. This is a great way to get involved in the Python community and to learn from other developers.
  • Attend meetups and conferences. This is a great way to meet other Python developers and to learn about new trends in Python programming.
  • Read books and articles about Python. This is a great way to stay up-to-date on the latest Python news and developments.
  • Get involved in the Python community. There are many ways to get involved in the Python community, such as attending meetups, participating in online forums, and contributing to open source projects. Getting involved in the community is a great way to learn from other developers and to get help when you need it.

Learning Python can be a challenging but rewarding experience. By following these tips, you can increase your chances of success.

Monday, 12 June 2023

What are the benefits of taking online Python classes over reading a book and doing exercises by yourself?

There are many benefits to taking online Python classes over reading a book and doing exercises by yourself. Here are a few of the most notable:

  • Structured learning: Online classes provide a structured learning environment that can help you stay on track and learn at your own pace. The classes are usually broken down into smaller modules, each of which covers a specific topic. This makes it easy to learn at your own pace and to focus on the areas that you need the most help with.
  • Expert instruction: Online classes are taught by experienced instructors who can answer your questions and help you understand the material. The instructors are usually available to answer questions through online forums, email, or live chat. This can be a great way to get help when you're stuck on a particular concept.
  • Community: Online classes offer a community of learners where you can ask questions, get help, and collaborate with others. This can be a great way to learn from others and to get feedback on your work.
  • Flexibility: Online classes can be taken at your own convenience, so you can fit them into your busy schedule. This can be a great option if you have a full-time job or other commitments.

Of course, there are also some potential drawbacks to taking online Python classes. Here are a few of the most notable:

  • Cost: Online classes can be more expensive than reading a book and doing exercises by yourself. However, the cost of online classes can be offset by the benefits that they offer, such as structured learning, expert instruction, and a community of learners.
  • Self-discipline: Online classes require a lot of self-discipline. You need to be motivated to learn and to complete the coursework on your own. If you're not self-disciplined, you may find it difficult to stick with an online class.
  • Technical difficulties: Online classes can sometimes be subject to technical difficulties. This can be frustrating and can interfere with your learning. However, most online classes have good customer support that can help you resolve any technical issues that you may encounter.

Overall, there are many benefits to taking online Python classes. If you're looking for a structured learning environment, expert instruction, a community of learners, and flexibility, then an online class may be the right choice for you.

What are attributes in Python, and how are they different from functions? How do you access attributes in Python, and what are they used for?

In Python, attributes are variables that are associated with an object. They can be used to store data or to define methods. Functions are also variables, but they are used to define blocks of code that can be executed.

Attributes and functions are different in a few ways. First, attributes are always associated with an object, while functions can be defined at the module level or within a class. Second, attributes can store data, while functions cannot. Third, attributes can be accessed using the dot notation, while functions must be called using the parentheses notation.

To access an attribute in Python, you use the dot notation. For example, if you have an object called my_object, and you want to access the attribute name, you would use the following code:

Code snippet
my_object.name

This would return the value of the name attribute.

Attributes are used for a variety of purposes. They can be used to store data, to define methods, or to customize the behavior of an object.

Here are some examples of how attributes can be used:

  • Storing data: You can use attributes to store data that is associated with an object. For example, you could create an attribute called name to store the name of a person, or an attribute called age to store the age of a person.
  • Defining methods: You can use attributes to define methods that are associated with an object. For example, you could create a method called greet() that would print a greeting when it is called.
  • Customizing the behavior of an object: You can use attributes to customize the behavior of an object. For example, you could create an attribute called is_active that would be used to determine whether or not an object is active.

Attributes are a powerful tool that can be used to store data, define methods, and customize the behavior of objects.