You get a bonus - 1 coin for daily activity. Now you have 1 coin

How to Correctly Connect a Third-Party API and Handle Errors

Lecture



Here we will look at the most important rules you need to follow when connecting to a third party API. How to correctly build your own (receiving) API will be covered in a separate article on our resource.

Connecting to a third-party API is the process of interacting with external services or data provided by other companies or developers. Here are the main rules and steps to consider when connecting to a third-party API:

  1. Getting access:

    • Register on the website or platform that provides the API in order to gain access to it.
    • Follow the instructions for obtaining an API key or access token. This key will be used for authentication with the API.
  2. Read the documentation:

    • Read the API documentation. It contains information about the available methods, parameters, request and response formats, as well as usage examples.
    • Make sure you understand how the API works and what capabilities it provides.
  3. Set the right rules:

    • Follow the rules and limitations established for using the API. These may include limits on the number of requests, rate-limiting periods and other usage rules.
  4. Security:

    • Ensure security when working with the API. Do not store API keys in plain text in your code and do not transmit them over unsecured communication channels.
    • Consider using HTTPS to protect the data transmitted between your application and the API.
  5. Error handling:

    • Take into account the possible errors that may occur when interacting with the API, and provide handling for them in your code.
    • Consider the errors returned by the API and give the user information about the problems that have occurred.
  6. Monitoring and debugging:

    • Implement monitoring of API usage in order to track performance and possible problems.
    • Use debugging tools to analyze API requests and responses when problems arise.
  7. Authorization:

    • If the API requires authorization, make sure you pass the correct credentials (API keys, tokens) in your requests.
  8. Legal compliance:

    • Make sure that your use of the API complies with the law and with the rules of the platform providing the API.
  9. Updates and support:

    • Stay informed about changes in the API and update your code when necessary.
    • Maintain your integration and fix any problems that arise.
  10. Testing:

    • Test your integration with the API before rolling it out to production, to make sure it is reliable and works correctly.

Following these rules will help you successfully connect and use a third-party API in your application or project.

The token used for authorization with a third-party API can be used both on the backend and on the frontend. On the backend, the data transmission channel and the data itself, including the token, are completely hidden from the outside world, so additional protection measures are often not required, apart from verifying the authenticity of the sender and of the data for incoming callback data (for example, webhooks).

When it comes to the correct and secure way of implementing frontend authorization using tokens, one of the important aspects is ensuring the reliability and protection of the tokens. For this purpose you can consider mechanisms that guarantee that your token cannot be used on another resource without your permission.

For this purpose you can use additional protection measures, such as checking the HTTP Referer, the sender's IP address, or even using an additional encrypted key. Here is how this can be described nicely:

"To ensure maximum security and protection of user tokens during frontend authorization, we apply additional verification measures. Our system not only checks the validity of the token, but also analyzes a number of additional parameters, including:

  1. HTTP Referer: We require that the token be used only on pages that have a matching Referer associated with our official domains. This guarantees that the token will not be passed to third-party resources without our permission.

  2. Sender's IP address: We also analyze the IP address of the request sender. If it does not match the trusted IP addresses that we have specified, the request will be rejected. This prevents unauthorized access even when a valid token is present.

  3. Additional encrypted key: For an extra level of security we can use an encrypted key together with the token. This key must be decrypted on the server, and if it does not match the expected value, the request will be rejected.

These additional verification measures guarantee that our tokens remain secure and cannot be abused on third-party resources. We pay great attention to security in order to protect the privacy and data of our users.

Since it is impossible to guarantee that a third-party API will work 100% of the time, you need to be prepared in advance for the fact that the third-party API will produce errors. These must be taken into account already at the development stage of your application that connects to the third-party API, and during testing. Errors can occur at three levels. The first level: the third-party API returns a previously declared form of response (HTTP header and response body). The second level of errors you must be ready for: the third-party API returns a completely non-standard response body or HTTP header. Even so, your application must still accept the response and must not stop working; for example, when exceptions occur in JavaScript and are not caught, execution may be interrupted and all the features on your page may stop working entirely. And the third level: the third-party API either responds with a very long timeout or provides no response at all. This is likewise solved by catching exceptions, setting a timeout and using default values, with mandatory logging and notification of DevOps, system administrators or the security team.

The importance of error handling when interacting with a third-party API, and the types of errors in such interaction.

Effective error management can significantly increase the reliability and stability of your application.

How to Correctly Connect a Third-Party API and Handle Errors

How to Correctly Connect a Third-Party API and Handle Errors

How to Correctly Connect a Third-Party API and Handle Errors

Here is how you are required to handle potential errors at the different levels:

  1. Errors of the first kind (Level 1) — errors with predefined responses:

    • Analyze the API documentation to understand which errors may occur and which responses are expected.
    • Create a mapping of API errors to the standard errors in your application.
    • Develop a strategy for how to behave when these errors occur, including notifying the user or recording events in a log.
  2. Errors of the second kind (Level 2) — non-standard responses:

    • Try to anticipate the possibility of non-standard responses, handling them flexibly and without interrupting the application.
    • Use response structure validation mechanisms to make sure the responses match the expected formats, and if they do not, handle such cases taking the specifics of the API into account.
    • Consider implementing a refactoring mechanism or adapters in order to normalize API responses into a standard format that will be easier to process.
  3. Errors of the third kind (Level 3) — errors related to timeouts and missing responses:

    • Set reasonable timeouts for API requests in order to avoid blocking and to keep the application running.
    • Use asynchronous processing mechanisms to manage long requests and avoid blocking the application's main thread.
    • Develop mechanisms for automatically retrying requests when connection failures occur or responses are missing, taking into account certain limits and recovery scenarios.

Logging and notifications:

  • Set up detailed logging for all API requests and responses, as well as for error handling.
  • Notify the operations or support team in the event of serious errors or problems with the API, so that they can react to them quickly and resolve them.

Thus, to solve potential problems when using third-party APIs, you need to:

  • limit the connection timeout
  • catch errors
  • assign adequate default values
  • perform mandatory logging of caught errors

How to Correctly Connect a Third-Party API and Handle Errors

try {
    $ctx = stream_context_create(array('http'=>
        array(
            'timeout' => 2,  // Seconds
        )
    ));
    $addressName = file_get_contents(
        'https://intellect.icu/v1/api/addresses/' . $aid,
        false,
        $ctx
    );
} catch (\Exception $e) {
    \Log::critical($e->getMessage());
}
if(!$addressName){
    $addressName = 'default address' ;
}

It is also important to have well-structured and easily readable code in order to make debugging and error handling simpler. Error handling is an integral part of development, and understanding the possible problems and the ways to solve them at different levels will help you create a reliable and stable application.

Comments

To leave a comment

If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Lectures and tutorial on "Software and information systems development"

Terms: Software and information systems development