{"id":2058,"date":"2025-07-06T20:11:01","date_gmt":"2025-07-06T16:41:01","guid":{"rendered":"https:\/\/mshaeri.com\/blog\/?p=2058"},"modified":"2026-05-19T02:26:38","modified_gmt":"2026-05-19T12:26:38","slug":"make-python-api-calls-a-breeze-with-dequest-declarative-client","status":"publish","type":"post","link":"https:\/\/mshaeri.com\/blog\/make-python-api-calls-a-breeze-with-dequest-declarative-client\/","title":{"rendered":"Make Python API Calls a Breeze with dequest Declarative Client"},"content":{"rendered":"\n<p>Making HTTP requests in Python often involves repetitive code for handling parameters, authentication, retries, and error handling. In modern applications, making HTTP requests reliably is critical\u2014especially when dealing with microservices, third-party APIs, or distributed systems. What if we could encapsulate all of this in a declarative way while maintaining type safety and flexibility? <strong><code>dequest<\/code><\/strong> is here to save the day! With its <strong><code>@sync_client<\/code><\/strong> and <strong><code>@async_client<\/code><\/strong> decorators, you can make API calls declarative, elegant, and supercharged with caching, retries, and circuit breakers\u2014without dealing with <code><strong>requests<\/strong><\/code> or <code><strong>asyncio<\/strong><\/code> packages manually.<\/p>\n\n\n\n<p>In this post, I&#8217;ll show you how to:<\/p>\n\n\n\n<ul>\n<li>Use  <strong>sync \/ async<\/strong> API call easily<\/li>\n\n\n\n<li>Fetch data with <strong>zero boilerplate<\/strong><\/li>\n\n\n\n<li> Handle <strong>path, query, and form parameters<\/strong><\/li>\n\n\n\n<li>Use <strong>retries, circuit breakers, and caching<\/strong> for resilient async APIs<\/li>\n\n\n\n<li>Work with <strong>callbacks and fallbacks<\/strong><\/li>\n<\/ul>\n\n\n\n<p>Let\u2019s get started! <\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>1. Install <code>dequest<\/code> and Set Up<\/strong><\/h2>\n\n\n\n<p>First, install the package:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"bash\" class=\"language-bash\">pip install dequest\n<\/code><\/pre>\n\n\n\n<p>That\u2019s it! Now you\u2019re ready to make API calls like a boss.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>2. Fetching Data with sync_client<\/strong><\/h2>\n\n\n\n<p>Imagine you need to fetch a list of users <strong>by city<\/strong>. Normally, you\u2019d write a bunch of <code>requests.get()<\/code> calls, handle parameters, check for errors, and parse JSON. But with <code><strong>dequest<\/strong><\/code>, it\u2019s as simple as defining a function:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"python\" class=\"language-python\">from dequest import sync_client, QueryParameter\nfrom typing import List\nfrom dataclasses import dataclass\n\n@dataclass\nclass UserDto:\n    id: int\n    name: str\n    city: str\n\n\n@sync_client(url=\"https:\/\/jsonplaceholder.typicode.com\/users\", dto_class=UserDto)\ndef get_users(city: str = QueryParameter(alias=\"city_name\")) -> List[UserDto]:\n    pass  # No implementation needed!\n\nusers = get_users(city=\"New York\")\nprint(users)\n<\/code><\/pre>\n\n\n\n<p>Boom! \ud83c\udf87 This sends a <code>GET<\/code> request to:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"python\" class=\"language-python\">https:\/\/jsonplaceholder.typicode.com\/users?city_name=New%20York\n<\/code><\/pre>\n\n\n\n<p>\u2026and automatically maps the response to <code>UserDto<\/code> objects.<\/p>\n\n\n\n<p>\u2705 <strong>No manual request handling<\/strong><br>\u2705 <strong>No JSON parsing<\/strong><br>\u2705 <strong>No error handling needed (it\u2019s built-in!)<\/strong><\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>3. Using Path Parameters<\/strong><\/h2>\n\n\n\n<p>Need to fetch a single user by ID? Use <code><strong>PathParameter<\/strong><\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"python\" class=\"language-python\">from dequest import sync_client, PathParameter\n\n@sync_client(url=\"https:\/\/jsonplaceholder.typicode.com\/users\/{user_id}\", dto_class=UserDto)\ndef get_user(user_id: int = PathParameter()) -> UserDto:\n    pass\n\nuser = get_user(user_id=1)\nprint(user)\n<\/code><\/pre>\n\n\n\n<p>This generates:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"python\" class=\"language-python\">GET https:\/\/jsonplaceholder.typicode.com\/users\/1\n<\/code><\/pre>\n\n\n\n<p>Nice and clean, right?<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>4. Sending Data in a POST Request<\/strong><\/h2>\n\n\n\n<p>If you need to create a new user, just use <code><strong>FormParameter<\/strong><\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"python\" class=\"language-python\">from dequest import sync_client, FormParameter\nfrom dequest.enums import HttpMethod\n\n@sync_client(url=\"https:\/\/some-url-to-save-users\/users\", method=HttpMethod.POST, dto_class=UserDto)\ndef create_user(name: str = FormParameter(), city: str = FormParameter()) -> UserDto:\n    pass\n\nnew_user = create_user(name=\"Alice\", city=\"Berlin\")\nprint(new_user)\n<\/code><\/pre>\n\n\n\n<p>This will automatically send form data in a <code>POST<\/code> request. <\/p>\n\n\n\n<p>Want to send <strong>JSON instead<\/strong>? Use <code>JsonBody<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"python\" class=\"language-python\">from dequest import sync_client, JsonBody\n\n@sync_client(url=\"https:\/\/jsonplaceholder.typicode.com\/users\", method=\"POST\", dto_class=UserDto)\ndef create_user(name: str = JsonBody(), city: str = JsonBody()) -> UserDto:\n    pass\n\nnew_user = create_user(name=\"Alice\", \"city\"=\"Berlin\")\nprint(new_user)\n<\/code><\/pre>\n\n\n\n<p>The above function call, send this request to the url:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"bash\" class=\"language-bash\">curl -X POST https:\/\/some-url-to-save-users.com\/users \\\n      -H \"Content-Type: application\/json\" \\\n      -d '{\"name\": \"Alice\", \"city\": \"Berlin\"}'<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>5. Retrying Failed Requests<\/strong><\/h2>\n\n\n\n<p>Ever had an API randomly fail?  Instead of manually retrying, just tell <code><strong>dequest<\/strong><\/code> to automatically retry failed requests:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"python\" class=\"language-python\">@sync_client(url=\"https:\/\/api.example.com\/data\", retries=3, retry_delay=2.0,retry_on_exceptions=(HTTPError,))\ndef get_data():\n    pass\n<\/code><\/pre>\n\n\n\n<p>\ud83d\udd01 <strong>This will retry up to 3 times<\/strong>, with a <strong>2-second delay<\/strong> between attempts.<\/p>\n\n\n\n<p>Works for any <strong>HTTPError<\/strong>\u2014no extra code needed! If you need more control on retry we he <code>giveup<\/code> for specifying when and in which condition should the client raise error instead of retry:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"python\" class=\"language-python\">from dequest import async_client, HttpMethod\n from requests import HTTPError\n import http\n @async_client(\n     url=\"https:\/\/dummyjson.com\/auth\/me\",\n     method=HttpMethod.GET,\n     dto_class=UserDTO,\n     retries=3,\n     retry_delay=1,\n     retry_on_exceptions=(HTTPError,),\n     # Retry only if the error is an internal server error (500)\n     giveup=lambda e: e.response.status_code != http.HTTPStatus.INTERNAL_SERVER_ERROR,\n )\n def get_current_user() -&gt; UserDTO:\n     \"\"\"\n     Retrieve the current user's information from the API.\n     \"\"\"\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>6. Caching API Responses<\/strong><\/h2>\n\n\n\n<p>Why hit the server <strong>every time<\/strong> if the data doesn\u2019t change? Enable caching:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"python\" class=\"language-python\">@sync_client(url=\"https:\/\/api.example.com\/popular-posts\", enable_cache=True, cache_ttl=60)\ndef get_popular_posts():\n    pass\n<\/code><\/pre>\n\n\n\n<p> This caches the response for <strong>60 seconds<\/strong>\u2014saving API calls and speeding up the processes. It generates a <code>cache_key<\/code> by combining the URL, including the values of path parameters, with query parameters, ensuring that each API request is cached separately.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>7. Using a Circuit Breaker for Resilience<\/strong><\/h2>\n\n\n\n<p>Some APIs <strong>go down frequently<\/strong>. Instead of hammering a broken server, use a <strong>circuit breaker<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"python\" class=\"language-python\">from dequest import sync_client\nfrom dequest.circuit_breaker import CircuitBreaker\n\nbreaker = CircuitBreaker(failure_threshold=5, recovery_timeout=30)\n\n@sync_client(url=\"https:\/\/api.unstable.com\/data\", circuit_breaker=breaker)\ndef get_unstable_data():\n    pass\n<\/code><\/pre>\n\n\n\n<p>If the API <strong>fails 5 times<\/strong>, the circuit <strong>opens<\/strong> (blocks requests for 30 sec), after 30 sec, it <strong>resumes requests<\/strong> and checks if the API is back. This prevents <strong>overloading a failing service<\/strong>!<\/p>\n\n\n\n<p>If a <code><strong>CircuitBreaker<\/strong><\/code> instance is provided and disallows a request, the <strong>fallback<\/strong> function is invoked (if defined); otherwise, a <code><strong>CircuitBreakerOpenError<\/strong><\/code> is raised:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"python\" class=\"language-python\"> from dequest import sync_client\n from dequest.circuit_breaker import CircuitBreaker, CircuitBreakerOpenError\n\n # Define a fallback function that returns cached data\n def fallback_response():\n     return {\"message\": \"Service unavailable, returning cached data instead\"}\n\n # Create a Circuit Breaker instance with a fallback\n breaker = CircuitBreaker(\n     failure_threshold=3, \n     recovery_timeout=10, \n     fallback_function=fallback_response  # Set fallback at the CircuitBreaker level\n )\n\n @sync_client(\n     url=\"https:\/\/api.unstable.com\/data\",\n     circuit_breaker=breaker\n )\n def fetch_unstable_data():\n     pass\n\n # Simulating multiple failed requests\n try:\n     for _ in range(5):  # This will exceed the failure threshold\n         response = fetch_unstable_data()\n         print(response)\n except CircuitBreakerOpenError: # it won't raise\n     print(\"Circuit breaker is open! Too many failures, try again later.\")<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p><strong>Note<\/strong> : <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-red-color\">The retry logic wraps the entire operation so that only if all attempts fail does the circuit breaker record one failure.<\/mark><\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>8. <strong>Making Asynchronous API Calls with <code>async_client<\/code><\/strong><\/strong><\/h2>\n\n\n\n<p>Many times we just need hit an API and the result is not important for us, howeverm if we call the API with sync_client the system should wait for the call be finished to let the fellow go on. In such scenarios we can use @async_client decorator to make the API async without pain.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"python\" class=\"language-python\">\n\n@async_client(url=\"https:\/\/api.example.com\/notify\", method=HttpMethod.POST)\ndef notify():\n    pass\n\nnotify()\n<\/code><\/pre>\n\n\n\n<p>A great feature of <code>@async_client<\/code> is that you don\u2019t need to use it exclusively in an async function or execute it with <code>asyncio<\/code>. As shown in the example, you can simply call the function, and it handles everything for you. However, keep in mind that it won\u2019t wait for the result and will immediately proceed to the next line of code. If you want to automatically process responses whenever it got ready? Just pass a callback:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"python\" class=\"language-python\">async def process_data(data):\n    print(f\"Received data: {data}\")\n\n@async_client(url=\"https:\/\/api.example.com\/updates\", callback=process_data)\ndef get_updates():\n    pass\n<\/code><\/pre>\n\n\n\n<p>Every time <code>get_updates()<\/code> is called, <strong><code>process_data()<\/code> will run automatically<\/strong> with the response.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>9. Configuring dequest: Global Settings<\/strong><\/h2>\n\n\n\n<p>Dequest allows global configuration via DequestConfig, the configuration can be set using .config method of the DequestConfig class:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"python\" class=\"language-python\">from dequest import DequestConfig\n\nDequestConfig.config(\n&nbsp; &nbsp;cache_provider=\"redis\", # defaults to \"in_memory\"\n&nbsp; &nbsp;redis_host=\"my-redis-server.com\",\n&nbsp; &nbsp;redis_port=6380,\n&nbsp; &nbsp;redis_db=1,\n&nbsp; &nbsp;redis_password=\"securepassword\",\n&nbsp; &nbsp;redis_ssl=True,\n)<\/code><\/pre>\n\n\n\n<p>Using the <code>.config()<\/code> method is optional\u2014you can call it on app startup if you want to override the default settings with custom configurations.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Final Words<\/h2>\n\n\n\n<p><strong>Dequest<\/strong> makes API calls in Python clean, reliable, and fast. With decorators like <code>@sync_client<\/code> and <code>@async_client<\/code>, you get built-in support for retries, caching, circuit breakers, and more without the boilerplate. It&#8217;s production-ready and developer-friendly. Give it a try and simplify your service calls!<\/p>\n\n\n\n<p>Happy coding! \ud83d\ude80<\/p>\n\n\n\n<p><strong>References<\/strong>:<\/p>\n\n\n\n<ul>\n<li><a href=\"https:\/\/github.com\/birddevelper\/dequest\">Dequest github repository<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/dequest-documentation.readthedocs.io\/en\/latest\/index.html\">Dequest documentation<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/github.com\/birddevelper\/dequest_example\">Example Project<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>Making HTTP requests in Python often involves repetitive code for handling parameters, authentication, retries, and error handling. In modern applications, making HTTP requests reliably is &hellip; <\/p>\n","protected":false},"author":1,"featured_media":2156,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1,35,41],"tags":[97,306,298,299,300,301,67,304,39,305,302],"_links":{"self":[{"href":"https:\/\/mshaeri.com\/blog\/wp-json\/wp\/v2\/posts\/2058"}],"collection":[{"href":"https:\/\/mshaeri.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/mshaeri.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/mshaeri.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/mshaeri.com\/blog\/wp-json\/wp\/v2\/comments?post=2058"}],"version-history":[{"count":4,"href":"https:\/\/mshaeri.com\/blog\/wp-json\/wp\/v2\/posts\/2058\/revisions"}],"predecessor-version":[{"id":2381,"href":"https:\/\/mshaeri.com\/blog\/wp-json\/wp\/v2\/posts\/2058\/revisions\/2381"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/mshaeri.com\/blog\/wp-json\/wp\/v2\/media\/2156"}],"wp:attachment":[{"href":"https:\/\/mshaeri.com\/blog\/wp-json\/wp\/v2\/media?parent=2058"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/mshaeri.com\/blog\/wp-json\/wp\/v2\/categories?post=2058"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/mshaeri.com\/blog\/wp-json\/wp\/v2\/tags?post=2058"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}