Results 1 to 11 of 11

Thread: Need to learn how to read RESTAPI into VB6

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    Nov 2010
    Posts
    425

    Need to learn how to read RESTAPI into VB6

    I stumbled upon a website (finnhub.io) that provides free stock data via API (organized around REST).

    In VB6, I created a small calculator design and thought it would be a great idea to be able to enter a stock symbol and have it automatically fill in the current (or last) stock price.

    That's it. Just get the price. Once I learn how to do this I can expand later.

    =====

    The problem is, I have virtually no API, REST or JSON experience. Just a major noob in this area.

    I'd like to learn how to do the task listed above using VB6. There are vids on using Python and others, but naturally no VB6 (cuz it is old as dirt but I'm familiar with it).

    Can someone(s) direct me to perhaps resources that teach what I need to learn, perhaps in a logical order (jumping around subjects makes my brain melt)?

    Or perhaps have sample code on how VB6 could be used to access these Finnhub API data calls?

    TIA
    Last edited by webbiz; Aug 5th, 2022 at 02:00 PM.

  2. #2

    Thread Starter
    Hyperactive Member
    Join Date
    Nov 2010
    Posts
    425

    Re: Need to learn how to read RESTAPI into VB6

    While I am stumbling around gathering bits of information (overload!), I found example code in cURL and figured it would execute in Powershell. Good guess!

    So after getting an API key, I ran the following (mykey is of course my API key. Learned it should not be broadcasted.):

    PS C:\Users\Rick> curl "https://finnhub.io/api/v1/quote?symbol=AAPL&token=mykey"

    This returned the following information:

    StatusCode : 200
    StatusDescription : OK
    Content : {"c":165.02,"d":-0.56,"dp":-0.3382,"h":165.85,"l":163,"o":163.21,"pc":165.58,"t":1659
    728304}
    RawContent : HTTP/1.1 200 OK
    Connection: keep-alive
    Access-Control-Allow-Credentials: true
    Access-Control-Allow-Headers: Origin
    Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE
    Access-Control-All...
    Forms : {}
    Headers : {[Connection, keep-alive], [Access-Control-Allow-Credentials, true],
    [Access-Control-Allow-Headers, Origin], [Access-Control-Allow-Methods, POST, GET,
    OPTIONS, PUT, DELETE]...}
    Images : {}
    InputFields : {}
    Links : {}
    ParsedHtml : mshtml.HTMLDocumentClass
    RawContentLength : 92

    Okay, this looks good so far.

    So the data I am looking for is in the 'Content' part of this. "c":165.02

    Yep, I verified that Apple was at 165.02 at the time I ran this.

    **This is soooo cool. I'm easily impressed. All new to me.



    Obviously I could write a VB6 routine to parse this specifically for this EXACT response (grab the "c" value following 'Content', etc.), but that has to be really cheezy.

    I'm assuming that there are certain formalities (standards?) in processing this kind of data that allows for possible field differences, etc?

    And what would everyone recommend as the best way to SEND this line "https://finnhub.io/api/v1/quote?symbol=AAPL&token=mykey" in order to generate the response?

    I would appreciate all the clues, directions and suggestions from all you VB6 gurus.

    Thanks. :-)

  3. #3
    PowerPoster
    Join Date
    Feb 2017
    Posts
    4,302

    Re: Need to learn how to read RESTAPI into VB6

    It seems to be a Json. You can parse it with a Json parser.
    For example this one.

    And for the HTTP call, I suggest WinHttpRequest, search the forum for examples.

  4. #4

    Thread Starter
    Hyperactive Member
    Join Date
    Nov 2010
    Posts
    425

    Re: Need to learn how to read RESTAPI into VB6

    Quote Originally Posted by Eduardo- View Post
    It seems to be a Json. You can parse it with a Json parser.
    For example this one.
    Great! I was skimming through all the JSON parser posts and getting confused as to which/how to use.

    This looks easy enough for me to understand and use.

    Thanks!


    Any recommendations on sending the request to begin with? WinHttpRequest? Still sorting through posts on this.

  5. #5
    Junior Member
    Join Date
    Jul 2019
    Posts
    24

    Re: Need to learn how to read RESTAPI into VB6

    Long explanation:

    As they say on their developer documentation page (https://finnhub.io/docs/api), Finnhub's API is organized around REST requests (REST is a fancy way of saying that data is obtained by calling a Web page).

    They use the Swagger specification to make the requests, and even show a link to download their Swagger schema, which is at URL: https://finnhub.io/static/swagger.json.

    On the swagger specification page (https://swagger.io) you can find a schema editor: https://editor.swagger.io/

    The interesting thing about all this is that the schema editor allows you to test the calls where data is requested, and shows you an example with the curl utility that tells you the specific URL to call.

    The curl example is very easy to translate into VB6 code using the WinHTTPRequest library...

    Process to follow:

    Go to https://editor.swagger.io/, in the menu choose File --> Import URL and enter the URL https://finnhub.io/static/swagger.json.

    On the left you will see the swagger code (which is not interesting for us), and on the right the list of all available options. You can try any of them to see the calls to be made.

    As an example, when testing the call to /search with the symbol "SVXY" I see that the data can be obtained with the CURL utility:

    Code:
    curl -X 'GET' \
      'https://finnhub.io/api/v1/search?q=SVXY&token=dddd' \
      -H 'accept: application/json'
    Code in VB6:

    Code:
    Private Sub btnTest_Click()
        Dim URL As String
        Dim Req As WinHttpRequest, S As String
    
        URL = "https://finnhub.io/api/v1/search?q=SVXY&token=1234567890"
    
        Set Req = New WinHttpRequest
        With Req
            .Open "GET", URL, False
            .SetRequestHeader "accept", "application/json"
            .Send
            .WaitForResponse
    
            S = .ResponseText
        End With
        Set Req = Nothing
    End Sub
    The resulting data is in JSON, so you will need a library to process it. You have an example in the forum: https://www.vbforums.com/showthread....rser-Generator

    I hope this helps you...

  6. #6
    Junior Member
    Join Date
    Jul 2019
    Posts
    24

    Re: Need to learn how to read RESTAPI into VB6

    Gee, I see it took me so long to write the reply that you had already been answered...

  7. #7

    Thread Starter
    Hyperactive Member
    Join Date
    Nov 2010
    Posts
    425

    Re: Need to learn how to read RESTAPI into VB6

    Quote Originally Posted by LeoCV View Post
    Long explanation:


    I hope this helps you...
    Absolutely. THANKS!!

  8. #8

    Thread Starter
    Hyperactive Member
    Join Date
    Nov 2010
    Posts
    425

    Re: Need to learn how to read RESTAPI into VB6

    Quote Originally Posted by LeoCV View Post
    Gee, I see it took me so long to write the reply that you had already been answered...
    Answered, yes.

    But you added a whole bunch of things I was not understanding...like what this 'swagger' thing is. It was all greek to me.

    I'm like a big rock. It takes a bit of energy to get it rolling, but once it starts, it picks up momentum.

    I'm starting to see things a bit clearer now.

    So again, thanks for taking the time to help me out. :-)

  9. #9
    Junior Member
    Join Date
    Jul 2019
    Posts
    24

    Re: Need to learn how to read RESTAPI into VB6

    Happy to help

  10. #10
    PowerPoster
    Join Date
    Jun 2013
    Posts
    6,121

    Re: Need to learn how to read RESTAPI into VB6

    I always encapsulate such APIs in a Class, e.g. named cFinnApi -
    usually split into:
    - nice, speaking (low implementation-efforts requiring) Public Functions
    - and a Private Helper-Routine, which ensures the (JSON-Obj-returning) http-requests generically

    Code:
    Option Explicit
    
    Public ApiToken As String, TimeOutSeconds As Long
    
    'Demo-implementation of two Public Methods (both making use of a private, generic Helper-Routine)
    Public Function GetQuote(Symbol As String) As cCollection
      Set GetQuote = FinnhubGet("/quote", "symbol", Symbol)
    End Function
    
    Public Function GetStockMetric(Symbol As String, Optional Metric As String = "all") As cCollection
      Set GetStockMetric = FinnhubGet("/stock/metric", "symbol", Symbol, "metric", Metric)
    End Function
    
    'Helper-Routine for generic GET-Requests of the FinnHub-API (always returning a JSON-Object, also in the Error-Cases)
    'the ParamArray wants to be filled in "pairs": "paramname", paramvalue
    Private Function FinnhubGet(Path As String, ParamArray P()) As cCollection
        Const BaseURL = "https://finnhub.io/api/v1"
        
        Dim i As Long, Params As String, V, Req As WinHttpRequest
        For i = 1 To UBound(P) Step 2
            If VarType(P(i)) <> vbString Then V = Str(P(i)) Else V = P(i) '<- ensure locale-independent Number-conversion
            Params = Params & IIf(i > 1, "&", "?") & P(i - 1) & "=" & V
        Next
     
        With New WinHttpRequest
            .Open "GET", BaseURL & Path & Params, True
              .SetRequestHeader "X-Finnhub-Token", ApiToken '<- set the token in the header (not in the Param-List)
              .SetRequestHeader "accept", "application/json"
            .Send
            If Not .WaitForResponse(TimeOutSeconds) Then
              Set FinnhubGet = New_c.JSONObject
                  FinnhubGet.Prop("Err") = "Timeout for: " & Path & Params
            ElseIf .Status <> 200 Then
              Set FinnhubGet = New_c.JSONObject
                  FinnhubGet.Prop("Err") = "Status: " & .Status & " " & .StatusText & " for: " & Path & Params
            Else 'success! (return the decoded JSON-Body as a JSON-Collection)
               Set FinnhubGet = New_c.JSONDecodeToCollectionUTF8(.ResponseBody)
            End If
        End With
    End Function
    Once this Class is in place (as a Private Class in your Project) -
    your User-Code (here in a VB-Form), will then become quite easy:

    Code:
    Option Explicit
    
    Private oFinnAPI As New cFinnApi
    
    Private Sub Form_Load()
      oFinnAPI.ApiToken = "Your_API_Token"
      oFinnAPI.TimeOutSeconds = 5 'set the max. timeout, you want to wait for a response here
      
      Dim oQuote As cCollection: Set oQuote = oFinnAPI.GetQuote("AAPL")
      PrintJsonProps "oQuote-Props:", oQuote
      Debug.Print "direct-prop-access:", "c="; oQuote("c"); ", t="; DateAdd("s", oQuote("t"), "1970-01-01")
      
      Dim oMRoot As cCollection: Set oMRoot = oFinnAPI.GetStockMetric("AAPL", "all")
      PrintJsonProps "oMRoot-Props:", oMRoot
          Dim oSeries As cCollection: Set oSeries = oMRoot("series")
          PrintJsonProps "    oSeries-Props:", oSeries
          
          Dim oMetric As cCollection: Set oMetric = oMRoot("metric")
          PrintJsonProps "    oMetric-Props:", oMetric
    End Sub
    
    'helper-routine, which prints out returned JSON-Objects (or JSON-SubObjects)
    Private Sub PrintJsonProps(Title As String, ByVal oJson As cCollection)
      Debug.Print vbLf; Title
      Dim i As Long
      For i = 0 To oJson.Count - 1
        Debug.Print , oJson.KeyByIndex(i), IIf(IsObject(oJson.ItemByIndex(i)), "<object>", oJson.ItemByIndex(i))
      Next
    End Sub
    The JSON-decoding here (in both code-snippets) is done via the RC5 or RC6 JSON-support -
    so one needs two Project-references to run this demo:
    - vbRichClient5 (or alternatively RC6)
    - Mcrosoft WinHttp Request 5.1

    HTH

    Olaf

  11. #11

    Thread Starter
    Hyperactive Member
    Join Date
    Nov 2010
    Posts
    425

    Re: Need to learn how to read RESTAPI into VB6

    Quote Originally Posted by Schmidt View Post
    I always encapsulate such APIs in a Class, e.g. named cFinnApi -
    usually split into:
    - nice, speaking (low implementation-efforts requiring) Public Functions
    - and a Private Helper-Routine, which ensures the (JSON-Obj-returning) http-requests generically



    The JSON-decoding here (in both code-snippets) is done via the RC5 or RC6 JSON-support -
    so one needs two Project-references to run this demo:
    - vbRichClient5 (or alternatively RC6)
    - Mcrosoft WinHttp Request 5.1

    HTH

    Olaf
    Thank you Olaf. Your responses are always helpful and enlightening. :-)

    This should give me something to chew on.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width