8 Integrate third-party APIs

 

This chapter covers

  • Sending HTTP requests from your codebase
  • Authenticating at third-party APIs
  • Modeling structs for JSON responses
  • Sending multiple requests at once
  • Handling timeouts and retries
  • Integrating external HTTP calls in your route handlers

There is rarely a web service that doesn’t need to communicate with either third-party APIs or internally with other microservices. For this book, we are making HTTP requests to external APIs to demonstrate how that affects your codebase. It is up to you, after having a basic understanding of how to use HTTP crates in conjunction with Tokio, to find another crate able to talk the protocol of your choosing.

Use cases for sending HTTP requests can be as follows:

  • Shortening shared URLs in questions and answers
  • Verifying addresses when creating new accounts
  • Showing stock data when adding stock symbols in the questions/answers
  • Sending out emails or text messages when someone answers your question
  • Sending account creation emails

And these are just examples from our tiny application we built so far. Being able to send HTTP requests is important when you want to move toward using Rust in production. Another interesting use case is handling multiple HTTP requests at once. We will use our runtime of choice (Tokio) to join! various network requests and execute them in a bundle.

8.1 Preparing the codebase

8.1.1 Picking an API

8.1.2 Getting to know our HTTP crate

8.1.3 Adding an example HTTP call with Reqwest

8.1.4 Handling errors for external API requests

8.2 Deserializing JSON responses to structs

8.2.1 Gathering API response information

8.2.2 Creating types for our API responses

Summary