Troubleshooting API password issues when fetching a Json from an API using VBA in Excel

I'm facing challenges with an API that provides natural gas data. The documentation for this API can be found at . It allows me to access Json-formatted data by inputting a URL into my internet browser. However, in order to download the Json data, I need to use a "x-key" provided to me and execute a cURL command as shown in the example from the documentation:

"https://agsi.gie.eu/api/data/eu?from=2017-06-01&till=2017-06-14" --header "x-key: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

Our goal is to automate certain processes by creating a macro-enabled Excel document that can easily retrieve and utilize this information within Excel. Despite trying various VBA codes found on StackOverflow, I keep encountering an "access denied" error when interacting with the API. My assumption is that this issue arises due to incorrect input of the password (or "x-key"). The VBA code snippet I currently have includes references to JsonConverter and Base64Encode modules:

Sub test()

 Dim httpObject As Object
 Set httpObject = CreateObject("MSXML2.XMLHTTP")

 sUrl = "https://alsi.gie.eu/api/data/eu?from=2018-11-15&till=2018-12-04"
 sAuth = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

 sRequest = sUrl
 httpObject.Open "GET", sRequest, True
 httpObject.setRequestHeader "x-key", Base64Encode(sAuth)
 httpObject.send
 sGetResult = httpObject.responseText

 MsgBox sGetResult

 Dim oJSON As Object
 Set oJSON = JsonConverter.ParseJson(sGetResult)

 For Each sItem In oJSON
  dItemDate = oJSON(sItem)("date")
  sItemString = oJSON(sItem)("string")
  vItemValue = oJSON(sItem)("value")

  MsgBox "Item: " & sItem & " Date: " & dItemDate & " String: " & sItemString & " Value: " & vItemValue
 Next

End Sub

Despite attempting to apply Base64Encode to the password variable (sAuth) and trying different methods including without a password/key, I consistently receive the "access denied" message. This leads me to believe that the issue lies with the password entry. I am uncertain of how to proceed further, as this setup utilizing VBA seems to be the closest I have come to successfully retrieving data from this API within Excel. Your assistance is greatly appreciated.

Thank you.

Answer №1

Encoding the key is unnecessary. It's puzzling why your previous attempt failed; double check that you are passing False in the .Open line.

I observed that the response consists of dictionaries, but these dictionaries do not align with the keys specified in your script.

Option Explicit
Public Sub FetchJSON()
    Dim jsonData As Object   
    With CreateObject("MSXML2.XMLHTTP")
        .Open "GET", "https://agsi.gie.eu/api/data/eu?from=2017-06-01&till=2017-06-14", False
        .setRequestHeader "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT"
        .setRequestHeader "x-key", "APIkey"
        .send
        Set jsonData = JsonConverter.ParseJson(.responseText)
    End With
End Sub

Sample JSON data:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to extract information from a JSON array based on its length and content

Here is an example of some data: { "_id": ObjectId("528ae48e31bac2f78431d0ca"), "altitude": "110", "description": [ { "id": "2", "des": "test" } ], "id": "1", "latitude": "24.9528802429251", ...

JSON data in the RequestBody

Having issues converting JSON to a Java class. Controller @RequestMapping(value = "/{username}/add", method = POST) public void add(@RequestBody NoteModel note) { System.out.println(note.getTitle()); } JSON { title : "Title", te ...

Converting XML to JSON using JSON.Net

Here is the XML snippet I am working with: <?xml version="1.0" encoding="utf-8" ?> <XslMapper> <type name="article" xsl="http://localhost:8080/Xsl-a.xslt"> <category name="1234" xsl="http://localhost:8080/Xsl-b.xslt"></cat ...

Using Node.js to retrieve table data from a URL

My journey with Node JS and express is just beginning as I dive into building a website that serves static files. Through my research, I discovered the potential of using NodeJS with Express for this purpose. While I have successfully served some static HT ...

Restricting requests to only .json files is possible on an Apache server by using the

I am looking to implement a specific functionality on my live underdeveloped website that is accessible on the internet with remote access. This website produces both php/html content for human visitors and .json output for the API. My current requirement ...

Receiving empty string when extracting text from Span

Looking to extract text from the span within this specific div using Python and Selenium: <div class="product-name"> <span class="h1" itemprop="name">TARGET TEXT</span> </div> I attempted the following code, but it unfortunate ...

Determine the percentage using jQuery by considering various factors

I am facing an issue with the following code snippet: <script type="application/javascript"> $(document).ready(function () { $("#market_value").on("change paste keyup", function() { var market_value = par ...

The size of objects on canvas is not consistent when loading with fabric.js loadFromJSON

Click here to view the code var canvas = new fabric.Canvas('canvas_1'); var canvas2 = new fabric.Canvas('canvas_2'); var imgObj = new Image(); imgObj.src = "https://gtaprinting.ca/wp-content/uploads/2021/05/blank-t-shirt-front-gre ...

Ways to eliminate different types of Keys from JSON

Here is a snippet of the JSON data I am working with: { "expressions": { "storyId": "doesNotMatter" }, "facts": { } } I need to figure out how to remove the 'storyId' key from this JSON by converting it into a string and using Regex. Can an ...

Scrapy fails to retrieve closing prices from Yahoo! Finance

When attempting to extract closing prices and percentage changes for three tickers from Yahoo! Finance using Scrapy, I am encountering an issue where no data is being retrieved. I have verified that my XPaths are correct and successfully navigate to the de ...

What is the best way to display circles (generated from JSON data) in reverse order by incorporating a delay function?

I am currently working on creating an interactive visualization using circles that expand over a specified period, all centered at the same point. I have a script that generates these circles and saves the data in a JSON file. The smallest circle is posit ...

Exploring deeply nested objects in elasticsearch

Here's how my mapping is set up: "mappings": { "nodes": { "properties": { "createdAt": { "type": "date", "format": "dateOptionalTime" }, " ...

Tips for choosing the penultimate item in an unordered list using Selenium

Currently, I am involved in a selenium project where I need to scrape a website. The specific website contains an unordered list identified by the class name pagination. Here is how the code for the unordered list looks: <ul class="pagination" ...

Having trouble making JSON work alongside Ajax and jQuery?

In my JavaScript, I have the following code snippet... $.ajax({ type: 'POST', url: 'http://www.example.com/ajax', data: {email: val}, success: function(response) { alert(response); } }); The PHP fil ...

Developing a Web service in .NET 4.0 for fetching JSON data on Android devices

Currently, I am without any code at hand. My task involves building a webservice that can retrieve data from a database in JSON format to be used in an Android application. I'm feeling a bit lost on how to get started with this project. Any guidance o ...

AXE - Asp Xtreme Evolution - A cutting-edge JSON parser designed specifically for classic ASP development

Is there anyone who has successfully used this and got it to work? I'm encountering some issues with a JScript error and I'm unsure about how to resolve it. For more information on the product, you can refer to the following links. It's a J ...

Tips for Nesting Iterations in Java for JSONobjects

Currently, I have a JSON object called Station. I am using the keys() method to iterate over it to extract key-value pairs. However, I realize that I also need to iterate over the values themselves in order to capture every element of the value section. He ...

Converting JSON information into a structured database table

Seeking assistance with preprocessing a JSON file generated by YouTube's iframe API. The goal is to transform this JSON data into a pandas dataframe format, where each key from the JSON becomes a separate column and every recorded "event" translates t ...

Scrape the web using Python to automatically click the "load more" button until it no longer appears, collecting all tables and saving them in a CSV file

I am interested in downloading all tables from a specific website that lists all doctors in Paris. The website link is provided here: . To access all the names, it requires clicking on the "afficher plus de résultats" button multiple times until all resul ...

The data payload needed for sending a POST request in JSON format

I am in the process of constructing a body for a POST request relativeurl := "this-is-a-test-url" postBody := fmt.Sprintf("{\"requests\": [{\"httpMethod\": \"GET\",\"rela ...