Overview

8 Integrate third-party APIs

This chapter shows how to bring external HTTP services into a Rust web application and why that matters in real projects. It starts from the idea that many services need to talk to third-party APIs or other microservices, then walks through practical examples such as URL shortening, address verification, stock lookup, messaging, and email workflows. The main goal is to show how these calls affect the codebase, especially when they are introduced into route handlers that already manage database work and request processing.

A large part of the chapter focuses on choosing the right HTTP client and understanding its tradeoffs. It compares low-level and higher-level approaches, including Hyper and Reqwest, and recommends sticking with a client that fits the runtime already used by the application. The chapter also stresses the importance of testing API calls in a small helper project before integrating them into the main codebase, because Rust’s ownership model and type system can make mistakes surface early. Once a working request is found, the next steps are handling authentication, inspecting documentation carefully, and learning how to interpret both successful responses and failures from the external service.

The chapter then builds a complete integration around a profanity-checking API. It introduces typed response structures, custom error types, and logging so that internal failures can be distinguished from client-facing responses. After that, the profanity check is extracted into a reusable helper and applied to question and answer handlers, with content being censored before storage. Finally, the chapter explores more advanced concerns such as timeouts, retries with exponential backoff, and running multiple HTTP requests concurrently or in parallel using Tokio, reinforcing the idea that Rust’s strong typing and ecosystem help make external integrations safer and more maintainable.

An application like Postman lets you collect and save HTTP requests so you can easily refire them and therefore quickly test endpoints and workflows.
08-01
The documentation for the send method of the Reqwest crate, which states when this method throws an error
08-02
The documentation for error_for_status seems to return the possible API error we want.
08-03
We have to handle two errors in our flow: an internal crate error and nonsuccess (4xx,5xx) HTTP responses from the web service.
08-04
The online Transform tool can create Rust structs out of a given JSON.
08-05

Summary

  • Choosing an HTTP client depends partly on the runtime you chose for your project.
  • You can choose from various levels of abstraction when adding an HTTP client, depending on your needs.
  • Going with a widely used crate gives you the advantage of a richer ecosystem around the crate and more help on the internet.
  • Error handling is crucial when implementing HTTP calls to other services.
  • You don’t want to expose internal errors to clients.
  • You also don’t want to lose details when logging errors.
  • Rust gives you the option of handling errors internally and externally at the same time with different details.
  • Creating structs for responses and errors from your third-party API service helps future developers but also makes your codebase easier to study and extend, and prevents possible mistakes in the future.
  • Adding default retries of failed HTTP calls helps prevent the user from sending the same request multiple times a second.
  • The Tokio runtime exposes methods and macros to bundle futures to be able to work concurrently or in parallel (via join! or spawn).

FAQ

What is the main goal of integrating third-party APIs in a Rust web application?To let your service communicate with external systems, such as profanity filters, email services, address validation tools, or stock data providers, so your web app can offer richer features beyond its own database.
Which Rust HTTP client crates are highlighted in this chapter?The chapter mainly discusses Hyper and Reqwest. Hyper gives lower-level HTTP primitives, while Reqwest provides a more convenient, higher-level API and is often the preferred choice when using Tokio.
Why does the chapter recommend using a crate that matches your async runtime?Using a crate that fits your runtime, such as Tokio, avoids extra runtime complexity, extra OS threads, and harder-to-debug behavior. It keeps the application lighter and easier to maintain.
Why is API authentication important when calling third-party services?Most third-party APIs require authentication, usually through an API key sent in a header. The chapter shows that you often need to register, obtain a token, and include it in your request.
What is the purpose of the JSON feature in Reqwest?The JSON feature enables convenient serialization and deserialization support, which is useful when you want to parse API responses into Rust structs with typed fields.
Why does the chapter suggest creating a local helper project before integrating a new crate?It helps you experiment safely with the crate, test the happy path, and figure out whether the problem is in your code or in your understanding of the API before touching the main codebase.
Why can’t you implement a trait like Reject directly for reqwest::Error?Because Rust’s orphan rules prevent implementing a trait for a type you do not own. The solution is to wrap the external error in your own error enum and implement the needed trait on that type.
What is the difference between Reqwest request errors and HTTP error responses from the API?Reqwest errors usually mean the client request itself failed, such as network problems or authentication issues. HTTP 4xx and 5xx responses may still arrive successfully at the client level, so you must inspect the response status separately.
Why does the chapter use custom structs for API responses?Typed structs make the response easier to understand, safer to work with, and easier to extend. They also let Rust and Serde validate and deserialize the JSON response in a structured way.
How does the chapter improve performance when making multiple HTTP calls?It shows two approaches: `tokio::join!` for concurrent execution on the same thread and `tokio::spawn` for running tasks in separate async tasks. Both help process multiple requests more efficiently than doing them one by one.

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team - learn more


Close
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Rust Web Development Rust Web Development ebook for free
Close
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Rust Web Development Rust Web Development ebook for free
Close
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Rust Web Development Rust Web Development ebook for free