Sample code for 30+ languages & platforms
SQL Server

Moody's REST API - Get OAuth2 Token

See more Moody's Examples

Demonstrates how to get an OAuth2 access token for the Moody's REST API.

Chilkat SQL Server Downloads

SQL Server
-- Important: See this note about string length limitations for strings returned by sp_OAMethod calls.
--
CREATE PROCEDURE ChilkatSample
AS
BEGIN
    DECLARE @hr int
    DECLARE @iTmp0 int
    -- Important: Do not use nvarchar(max).  See the warning about using nvarchar(max).
    DECLARE @sTmp0 nvarchar(4000)
    DECLARE @success int
    SELECT @success = 0

    -- This example assumes the Chilkat API to have been previously unlocked.
    -- See Global Unlock Sample for sample code.

    DECLARE @http int
    EXEC @hr = sp_OACreate 'Chilkat.Http', @http OUT
    IF @hr <> 0
    BEGIN
        PRINT 'Failed to create ActiveX component'
        RETURN
    END

    DECLARE @req int
    EXEC @hr = sp_OACreate 'Chilkat.HttpRequest', @req OUT

    EXEC sp_OAMethod @req, 'AddParam', NULL, 'grant_type', 'password'
    EXEC sp_OAMethod @req, 'AddParam', NULL, 'scope', 'api/ratings api/addin rest'
    EXEC sp_OAMethod @req, 'AddParam', NULL, 'username', 'my_username'
    EXEC sp_OAMethod @req, 'AddParam', NULL, 'password', 'my_password'
    -- I have no idea of where to get the client_id or client_secret.
    -- When you create a Moody's App, it only provides an "API Key".
    EXEC sp_OAMethod @req, 'AddParam', NULL, 'client_id', 'my_client_id'
    EXEC sp_OAMethod @req, 'AddParam', NULL, 'client_secret', 'my_client_secret'

    EXEC sp_OASetProperty @req, 'HttpVerb', 'POST'
    EXEC sp_OASetProperty @req, 'ContentType', 'application/x-www-form-urlencoded'

    DECLARE @resp int
    EXEC @hr = sp_OACreate 'Chilkat.HttpResponse', @resp OUT

    EXEC sp_OAMethod @http, 'HttpReq', @success OUT, 'https://api.moodys.com/OAuth/Token', @req, @resp
    IF @success = 0
      BEGIN
        EXEC sp_OAGetProperty @http, 'LastErrorText', @sTmp0 OUT
        PRINT @sTmp0
        EXEC @hr = sp_OADestroy @http
        EXEC @hr = sp_OADestroy @req
        EXEC @hr = sp_OADestroy @resp
        RETURN
      END


    EXEC sp_OAGetProperty @resp, 'StatusCode', @iTmp0 OUT
    PRINT 'status code = ' + @iTmp0
    DECLARE @responseBody nvarchar(4000)
    EXEC sp_OAGetProperty @resp, 'BodyStr', @responseBody OUT

    PRINT @responseBody

    -- Save the JSON to a file for future requests.
    EXEC sp_OAGetProperty @resp, 'StatusCode', @iTmp0 OUT
    IF @iTmp0 = 200
      BEGIN
        DECLARE @fac int
        EXEC @hr = sp_OACreate 'Chilkat.FileAccess', @fac OUT

        EXEC sp_OAGetProperty @resp, 'BodyStr', @sTmp0 OUT
        EXEC sp_OAMethod @fac, 'WriteEntireTextFile', @success OUT, 'qa_data/tokens/moodys.json', @sTmp0, 'utf-8', 0
      END

    EXEC @hr = sp_OADestroy @http
    EXEC @hr = sp_OADestroy @req
    EXEC @hr = sp_OADestroy @resp
    EXEC @hr = sp_OADestroy @fac


END
GO