Can you provide some pseudo code for OAuth 2.0 implementation of client access to Digi-Key API?

*Update:

Please visit Digi-Key Electronics' GitHub page for a C# Api Client Library with OAuth2

https://github.com/digikey/ApiClient

~~~~~~~~~~~~~~~~~~~

Here is a simple pseudo code for OAuth2 and Digikey API example (given you already have a access token and refresh token).
 
        Function DigiKeyPartSearch(....)
        {
           if (Current AccessToken is expired or close to expiring) then
               Get new AccessToken and RefreshToken from current RefreshToken
               // Might want to save the new tokens and ExpiredIn property.
           endif
         
           Call Digikey endpoint with AccessToken.
 
           If (Call to Digikey endpoint errors with (401) and expired AccessToken) then
               Get new AccessToken and RefreshToken from current RefreshToken
               // Might want to save the new tokens and ExpiredIn property.
 
               Call Digikey endpoint with AccessToken
               If (call fails) then
                     Handle error and check logs to see what problem is..
               endif
           endif
          
           Display PartSearch Response...
         }

The proper way would be not to have to check “if the token is expired” before every call; this process should be offloaded to an OAuth thread. The thread will keep the token up-to-date and would be doing the token refresh. The main thread should only have to worry about the token if it ever gets a 401. If the main thread gets a 401, it will call the OAuth thread to get a new token.
 
As always there is the single threaded approach too, which will do a lot of blocking but I guess it will work.

categories: