A practical logging tip for API integrations

In this post, I’m looking to share a tip on logging when building good software that I’ve come to realize over the years. One of the most common things I have to do as a developer and programmer are integrations with APIs.

For both development and production purposes, it is extremely useful to log outgoing API calls. Why? Let’s run through an example!

Let’s say you are building a web application and you are leveraging a microservice architecture (e.g. your app calls an external OAuth service to serve authorization calls for the user to login to your app).

  1. If a user reports a production issue, you can easily go into your application logs and find out if the request was even made to OAuth service. This is especially useful if you do not own the other service because it is not practical for you to reach out to the service provider to ask if the request reached their server. Even if you do own the other service, you still have to complete an extra step of going into the other system and searching through the logs, and often times there are so many requests you can’t even easily tell which one came from your application.
  2. If you are reproducing issues on production or development (especially in automated tests), you can easily retry the request because you have the exact URL that is called. This is a significant quality of life improvement for you as the developer. What I find is that you are pretty always calling the API not as a hardcoded string but something like this: Config::get($_ENV['HOST_NAME']) . '/' . Config::get($_ENV['API_VERSION']) . '?term=' . $this->searchTerm, which is a huge nuisance if the call fails because you do not have the URL handy. In this example alone, there are so many different reasons the API call fail just from the improper construction of the URL, (e.g. there’s a bug in the config class, HOST_NAME is not set properly, API VERSION is not set properly, term is not set properly, and the list goes on).
  3. If you need to answer questions from a security audit, you can easily tell from the application logs what calls were made to the external service.
  4. If you are actively developing the application and there is a caching feature, logging the API calls makes it easier to tell if you are using a cached response or fresh response from the external service.

So there! I hope that performing this quick and easy step of logging your API calls can save you a lot of headaches and debugging time down the road.