Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do we use restful APIs from Excel macros (vba)?

Tags:

rest

excel

vba

Is there a plugin or library that could be used to access restful APIs from excel (probably using macros) and then store the responses somewhere (probably in a sheet).

Pardon the missing sample code. I'm not a VBA programmer.

like image 302
AndroidMechanic - Viral Patel Avatar asked Jul 07 '16 13:07

AndroidMechanic - Viral Patel


People also ask

What is API in Excel VBA?

API stands for Application Programming Interface. API's for VBA imply a set of methods that allow direct interaction with the operating system. System calls can be made by executing procedures defined in DLL files.

How does API work with Excel?

To import this on excel go to Data>Get Data>From other Sources> From Web or simply Data>From Web. Paste the API URL on the prompt then click OK. Then select Into Table on the Convert tab. Select the Value of Data then right click>Drill Down.

Can I make an API call from Excel?

Calls to external APIs can only be made through the Excel application, not through Power Automate under normal circumstances.


1 Answers

You can use the MSXML library within VBA. Then you can create an XMlHTTP request and do a GET or POST etc. Here's a code sample below. It uses late binding i.e. no need to reference the library first:

Option Explicit  Sub Test_LateBinding()      Dim objRequest As Object     Dim strUrl As String     Dim blnAsync As Boolean     Dim strResponse As String      Set objRequest = CreateObject("MSXML2.XMLHTTP")     strUrl = "https://jsonplaceholder.typicode.com/posts/1"     blnAsync = True      With objRequest         .Open "GET", strUrl, blnAsync         .SetRequestHeader "Content-Type", "application/json"         .Send         'spin wheels whilst waiting for response         While objRequest.readyState <> 4             DoEvents         Wend         strResponse = .ResponseText     End With      Debug.Print strResponse  End Sub 

I'm using this testing website - JSONPlaceholder - to call a RESTful API. This is the response:

enter image description here

Note that I found that calls to this website with this method fail if you a) make a synchronous request, or b) use http not https.

like image 146
Robin Mackenzie Avatar answered Nov 10 '22 06:11

Robin Mackenzie