API Integration
.
12
Mins Read

Python Function Wrappers and Decorators, Explained with API Examples

A Python function wrapper runs code before and after another function without changing it. This guide builds wrappers and decorators step by step, then uses them for API calls: retries, auth headers, rate limits and caching. Every sample was run on Python 3.14.

Dhayalan Subramanian
Associate Director - Product Growth at DigitalAPI
.
30 November 2026
In this blog
Share blog
TL;DR:

What is a Python function wrapper?

A Python function wrapper takes another function, adds behaviour before or after it, and returns a new function. The @decorator syntax applies a wrapper in one line.

Add functools.wraps so the wrapped function keeps its name and docstring.
Python
def wrap(func):
    def wrapper(*args, **kwargs):
        print("before", func.__name__)
        return func(*args, **kwargs)
    return wrapper

Your service calls a payments API in twelve places. Each call needs a retry, an auth header and a timeout. Someone copies the same eight lines into every call site. Then the retry logic changes, and you fix it in twelve places, or eleven.

A Python function wrapper fixes this. You write the retry once and apply it with one line. Python is the language most likely to face this problem: 57.9% of respondents to the Stack Overflow 2025 Developer Survey used it.

This guide builds wrappers from scratch, then turns them into four decorators for API calls. Every sample below was run on Python 3.14, and the output shown is real.

diagram of a Python function wrapper showing a call passing through before-code, the original function and after-code, then returning the result

What is a Python function wrapper?

A Python function wrapper is a function that wraps another function to add behaviour without editing it. It receives the original function, defines an inner function that calls it, and returns that inner function.

Definition

Wrapper function

A wrapper function exists to call another function, adding steps before or after the call. In Python, wrappers work because functions are objects: you can pass them as arguments, return them and store them in variables.

The word "wrapper" means the same thing in plain English: a layer around something that leaves the inside intact. A Python wrapper can log calls, check inputs, time execution, retry failures or cache results. The wrapped function does not know the wrapper exists.

Do not confuse this with an API wrapper. An API wrapper is a client library around an HTTP API. A wrapper function in Python wraps a single function. You often use the second to build the first.

How do you create a wrapper function in Python?

To create a wrapper, define an outer function that takes func. Inside it, define wrapper(*args, **kwargs) that calls func, then return wrapper. The *args, **kwargs signature lets the wrapper accept any arguments and pass them through.

Here is a wrapper applied by hand, without decorator syntax:

Python
def log_calls(func):
    def wrapper(*args, **kwargs):
        print(f"Calling {func.__name__} with {args}")
        result = func(*args, **kwargs)
        print(f"{func.__name__} returned {result}")
        return result
    return wrapper

def add(a, b):
    """Add two numbers."""
    return a + b

add = log_calls(add)   # wrap by hand
add(2, 3)
print(add.__name__, add.__doc__)

Output:

Output
Calling add with (2, 3)
add returned 5
wrapper None

The wrapper works, but look at the last line. The function now reports its name as wrapper and has lost its docstring. Logs, tracebacks and test tools will show the wrong name. The next section fixes that.

What are Python decorators, and why use functools.wraps?

Python decorators are wrappers applied with the @ syntax. functools.wraps copies the original function's name, docstring and metadata onto the wrapper. Writing @log_calls above a function is the same as add = log_calls(add) after it.

The @ syntax arrived with PEP 318 in Python 2.4. It moved the wrapping next to the function definition, where readers can see it.

Python
import functools

def log_calls(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        print(f"Calling {func.__name__} with {args}")
        return func(*args, **kwargs)
    return wrapper

@log_calls
def add(a, b):
    """Add two numbers."""
    return a + b

print(add(2, 3))
print(add.__name__, "|", add.__doc__)
print(add.__wrapped__(2, 3))

Output:

Output
Calling add with (2, 3)
5
add | Add two numbers.
5

The name and docstring are back. functools.wraps also sets __wrapped__, which points to the original function. The last line calls it directly and skips the logging. That attribute matters when you test decorated code.

Rule of thumb: put @functools.wraps(func) on every wrapper you write. It costs one line and prevents confusing logs.

How do you write a decorator with arguments?

A decorator with arguments is a function that returns a decorator. You add one more layer: the outer function takes the settings, the middle one takes func, and the inner one wraps the call.

Python
import functools

def tag(label):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            return f"[{label}] {func(*args, **kwargs)}"
        return wrapper
    return decorator

@tag("orders-api")
def status(order_id):
    return f"order {order_id} shipped"

print(status(7))

Output:

Output
[orders-api] order 7 shipped

@tag("orders-api") first calls tag("orders-api"). That returns decorator, which Python then applies to status. Every API decorator below uses this three-layer shape, so you can set retries, limits or timeouts per function.

diagram of the three nested functions in a Python decorator with arguments, from the settings layer to the decorator to the wrapper that runs the call

How do you write a Python retry decorator with backoff?

A Python retry decorator catches temporary errors, waits, and calls the function again, with the wait growing after each failure. Exponential backoff with jitter stops many clients from retrying at the same moment.

Python
import functools
import random
import time

def retry(times=3, base_delay=0.1, exceptions=(ConnectionError, TimeoutError)):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            for attempt in range(1, times + 1):
                try:
                    return func(*args, **kwargs)
                except exceptions as exc:
                    if attempt == times:
                        raise
                    delay = base_delay * 2 ** (attempt - 1)
                    delay += random.uniform(0, delay)  # jitter
                    print(f"Attempt {attempt} failed ({exc}); retrying in {delay:.2f}s")
                    time.sleep(delay)
        return wrapper
    return decorator

calls = {"n": 0}

@retry(times=4, base_delay=0.1)
def fetch_order(order_id):
    calls["n"] += 1
    if calls["n"] < 3:  # fail twice, then succeed
        raise ConnectionError("503 from upstream")
    return {"id": order_id, "status": "shipped"}

random.seed(1)
print(fetch_order(42))

Output:

Output
Attempt 1 failed (503 from upstream); retrying in 0.11s
Attempt 2 failed (503 from upstream); retrying in 0.37s
{'id': 42, 'status': 'shipped'}

Three rules keep retries safe:

  • Retry only temporary errors. Connection errors, timeouts, 429 and 503 are worth a retry. A 400 or 401 will fail again.
  • Retry only idempotent calls. A GET is safe. A POST that creates an order can charge twice unless the API supports idempotency keys.
  • Cap the attempts. Unlimited retries turn one outage into a traffic flood.

For production, the tenacity library offers the same pattern with stop, wait and retry conditions. Version 9.2.1 was released on PyPI on 7 Oct 2026. The older backoff library still works, but its last release, 2.2.1, dates from October 2022.

How do you add auth headers with a decorator?

An auth decorator reads a token from the environment and adds it to the request headers. No call site handles secrets. It keeps tokens out of source code and out of every function signature.

Python
import functools
import os

def with_auth(env_var="ORDERS_API_TOKEN"):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, headers=None, **kwargs):
            token = os.environ.get(env_var)
            if not token:
                raise RuntimeError(f"Set {env_var} before calling {func.__name__}")
            headers = {**(headers or {}), "Authorization": f"Bearer {token}"}
            return func(*args, headers=headers, **kwargs)
        return wrapper
    return decorator

@with_auth()
def get_order(order_id, headers=None):
    # In real code: return requests.get(url, headers=headers, timeout=10).json()
    return {"id": order_id, "sent_headers": headers}

os.environ["ORDERS_API_TOKEN"] = "test-token-123"  # demo only; set it in your shell
print(get_order(42, headers={"Accept": "application/json"}))

Output:

Output
{'id': 42, 'sent_headers': {'Accept': 'application/json', 'Authorization': 'Bearer test-token-123'}}

The decorator merges the token into any headers the caller passes. It fails fast with a clear message if the variable is missing. Never paste the token into the code itself. Our guide to hardcoded API keys explains how leaked keys get found and abused.

How do you rate limit API calls on the client side?

A rate limit decorator spaces out calls so your client never sends more than a set number per second. It prevents 429 errors before the server has to send them.

Python
import functools
import threading
import time

def rate_limit(calls_per_second):
    interval = 1.0 / calls_per_second
    lock = threading.Lock()
    last = [0.0]
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            with lock:
                wait = last[0] + interval - time.monotonic()
                if wait > 0:
                    time.sleep(wait)
                last[0] = time.monotonic()
            return func(*args, **kwargs)
        return wrapper
    return decorator

@rate_limit(calls_per_second=5)
def ping(i):
    return i

start = time.monotonic()
for i in range(6):
    ping(i)
print(f"6 calls took {time.monotonic() - start:.1f}s")

Output:

Output
6 calls took 1.0s

The first call runs at once, and the next five wait 0.2 seconds each. The lock keeps the limit correct across threads in one process. It does not coordinate across processes or servers; for that, the API side must enforce the limit. Our guide to API rate limiting vs throttling covers how servers do it.

How do you cache API responses with a decorator?

A caching decorator stores each result by its arguments and returns the stored copy until it expires. It cuts repeat calls for data that changes slowly, such as exchange rates or product catalogs.

Python
import functools
import time

def ttl_cache(seconds):
    def decorator(func):
        store = {}
        @functools.wraps(func)
        def wrapper(*args):
            hit = store.get(args)
            if hit and time.monotonic() - hit[1] < seconds:
                return hit[0]
            result = func(*args)
            store[args] = (result, time.monotonic())
            return result
        return wrapper
    return decorator

calls = {"n": 0}

@ttl_cache(seconds=60)
def get_exchange_rate(currency):
    calls["n"] += 1  # stands in for a network call
    return {"USD": 1.0, "EUR": 0.92}[currency]

for _ in range(3):
    get_exchange_rate("EUR")
print("upstream calls:", calls["n"])

Output:

Output
upstream calls: 1

Three calls reached the upstream once. The standard library's functools.lru_cache and functools.cache work too, but they never expire entries. Use a time limit for anything an API can change.

In what order should you stack API decorators?

Decorators apply from the bottom up, and the top one runs first on each call. For API calls, put the cache on top, then retry, then rate limit, then auth.

Python
@ttl_cache(seconds=60)    # 1. cached hits skip everything below
@retry(times=3)           # 2. each retry passes through the limiter
@rate_limit(calls_per_second=5)
@with_auth()              # 4. every attempt gets a fresh header
def get_order(order_id, headers=None):
    ...

With retry above the rate limiter, retries cannot burst past your limit. With the cache on top, a hit never touches the network.

stack of four Python decorators on an API function in order cache, retry, rate limit and auth, with arrows showing the call path down and the result path up

How do you test a Python function wrapper?

Test the decorator's behaviour through the decorated function, and test the original logic through __wrapped__. Feed the function a scripted sequence of failures so tests run fast with no network.

Python
import functools

def retry(times=3):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            for attempt in range(1, times + 1):
                try:
                    return func(*args, **kwargs)
                except ConnectionError:
                    if attempt == times:
                        raise
        return wrapper
    return decorator

@retry(times=3)
def fetch(results):
    value = results.pop(0)
    if isinstance(value, Exception):
        raise value
    return value

def test_retries_then_succeeds():
    assert fetch([ConnectionError(), ConnectionError(), "ok"]) == "ok"

def test_gives_up_after_three():
    try:
        fetch([ConnectionError()] * 3)
    except ConnectionError:
        return
    raise AssertionError("expected ConnectionError")

def test_original_is_reachable():
    assert fetch.__wrapped__(["raw"]) == "raw"

for t in (test_retries_then_succeeds, test_gives_up_after_three, test_original_is_reachable):
    t()
    print(t.__name__, "passed")

Output:

Output
test_retries_then_succeeds passed
test_gives_up_after_three passed
test_original_is_reachable passed

The same test_ functions run unchanged under pytest. In real suites, make the sleep injectable or patch time.sleep, so backoff does not slow your tests.

When should you write your own decorator, and when should you not?

Write your own decorator for small, local rules; move shared API policy to a library or to the gateway. A decorator only protects the code that uses it.

Write your own decorator if:

  • The rule is specific to one client, such as a tag, a timer or a local cache.
  • You want zero dependencies in a small script or library.
  • The logic fits in 20 lines and you can test it fully.

Use a library or move the rule to the API layer if:

  • You need jitter, stop rules and async support, which tenacity already handles.
  • Many teams call the same API. Each client then re-implements auth and limits, and they drift apart.
  • The limit must hold across servers. A client-side decorator cannot see other processes.

Server-side rules belong at the gateway. The DigitalAPI API Gateway supports OAuth, OIDC and mTLS, and applies separate rate limits per consumer, including AI agents. Clients keep thin decorators for retries and caching, and the gateway enforces the rest for everyone. If you are choosing a framework for the API itself, see our best Python API frameworks.

See how DigitalAPI enforces auth and rate limits for every API consumer at the gateway → Book a Demo

Key takeaways

  • A Python function wrapper adds behaviour around a function without changing it. Decorators apply wrappers with the @ syntax.
  • Always use functools.wraps. It keeps the function's name and docstring and exposes __wrapped__ for tests.
  • Decorators with arguments add one layer: settings, then decorator, then wrapper.
  • A Python retry decorator needs backoff, jitter and a cap, and should retry only temporary errors on idempotent calls.
  • Stack API decorators as cache, retry, rate limit, auth, from top to bottom.
  • Client decorators protect one client. Enforce shared auth and limits at the API gateway.

Frequently asked questions

1. What is a wrapper function?

A wrapper function is a function whose main job is to call another function, adding steps before or after the call. In Python, a wrapper takes the original function as an argument, defines an inner function that calls it, and returns that inner function. Wrappers are used for logging, timing, retries, caching and access checks.

2. How do you create a wrapper in Python?

Define an outer function that takes func. Inside it, define wrapper(*args, **kwargs) that runs your extra code and calls func(*args, **kwargs). Return wrapper. Decorate the inner function with functools.wraps(func) to keep the original name and docstring. Apply it with @your_decorator above any function.

3. What does wrapper mean in Python?

In Python, a wrapper is code that surrounds a function, object or library to add behaviour or a simpler interface. A function wrapper wraps one function. An API wrapper is a client library that wraps an HTTP API. A class wrapper wraps an object. In each case, the wrapped code stays unchanged.

4. What is the difference between a wrapper and a decorator in Python?

A wrapper is the inner function that runs around the original call. A decorator is the function that builds and returns that wrapper. The @decorator syntax applies it at definition time. In everyday use, developers often call both "decorators", and the terms overlap.

5. What does functools.wraps do?

functools.wraps copies the original function's metadata onto the wrapper. That includes __name__, __doc__, __module__, __qualname__ and __dict__. It also sets __wrapped__ to the original function. Without it, every decorated function reports its name as wrapper, which confuses logs, tracebacks and tests.

6. How do you write a Python retry decorator?

Write a decorator factory that takes the number of attempts and a base delay. In the wrapper, call the function in a loop. Catch only temporary errors, such as connection errors and timeouts. Sleep with exponential backoff plus random jitter between attempts. Re-raise the error after the last attempt.

7. Should I use tenacity or write my own retry decorator?

Write your own for small scripts and simple rules, since it needs no dependency and fits in about 20 lines. Use tenacity for production services that need async support, stop conditions, custom waits and logging hooks. Tenacity 9.2.1 was the latest version on PyPI on 27 November 2026.

8. Can a Python decorator take arguments?

Yes. Write a function that takes the arguments and returns a decorator. That decorator takes the function and returns the wrapper. Using @retry(times=3) first calls retry(times=3), then applies the returned decorator to the function below it.

Conclusion

A Python function wrapper is a small idea with a large payoff. You write a behaviour once, such as a retry, an auth header, a rate limit or a cache, and apply it with one line.

Start with the four API decorators above and add functools.wraps to each. Test them with scripted failures, not live calls. Stack them in the order shown, so retries respect limits and cache hits skip the network.

Then decide what belongs in the client at all. Rules every consumer must follow, such as authentication and per-consumer limits, are easier to enforce once at the gateway than in every codebase.


Stop hand-rolling auth and rate limits in every client: enforce them at the DigitalAPI gateway. Enforce auth and rate limits at the gateway

Prefer a walkthrough?
Book a Demo
About the author
Dhayalan Subramanian

Dhayalan Subramanian is Associate Director, Product Growth at DigitalAPI, where he leads go-to-market and product growth for the company’s multi-gateway API management platform. His work focuses on helping large enterprises and mid-market cloud companies consolidate APIs across AWS, Azure, Apigee, Kong, MuleSoft, and other gateways into a single control plane for governance, discovery, monetization, and agent consumption.

‍

Dhayalan brings 14+ years of experience across product strategy, enterprise architecture, and engineering leadership. Earlier in his career, he held senior roles at Encora (as Associate Architect and Technical Manager), Mindtree (Technology Lead), Tech Mahindra (Technical Lead), and Primus Analytics, where he designed integration frameworks and delivered enterprise-grade digital platforms for global customers.

‍

At DigitalAPI, he works directly with platform, integration, and developer experience leaders at Fortune 500 organizations to operationalize unified API catalogs, developer portals, and MCP-ready APIs. He writes regularly on API developer experience, API governance, and AI agent architectures.

Become AI-ready
Make every API agent-callable.
An 8-week pilot. We connect to your gateways, ship MCP-callable APIs, and onboard your first agent.
0 rip-and-replace
Same auth, same audit
Live in production in 8 weeks
Get started

One email a fortnight. Worth opening.

A short digest of what we're writing, what we're learning from customers, and the handful of links you'd actually want from us. No tracking pixels.

Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.