How to use online API ?

Just starting out? Need help? Post your questions and find answers here.
Walko
User
User
Posts: 11
Joined: Thu Mar 26, 2020 6:08 pm

How to use online API ?

Post by Walko »

Hello,

I work in the electronics industry but there is a lot of tension on the supply of components.
A reseller I order a lot from is called MOUSER and provides an API to run search queries which would be really great for tracking the amount of components still available.

They have examples where I can input a part number like the STM32F407VET6 like that :

Code: Select all

{
  "SearchByPartRequest": {
    "mouserPartNumber": "STM32F407VET6",
    "partSearchOptions": "string"
  }
}
the generated querie gives that (I have hidden the api key) :

Code: Select all

curl -X POST "https://api.mouser.com/api/v1/search/partnumber?apiKey=xxxxxxxxxx" -H  "accept: application/json" -H  "Content-Type: application/json" -d "{  \"SearchByPartRequest\": {    \"mouserPartNumber\": \"STM32F407VET6\",    \"partSearchOptions\": \"string\"  }}"
I have several questions :
How to manage strings with several symbols """" ?? if I create a single variable with the entire URL, purebasic does not like it.
how can i generate this command with Purebasic ?
I will try with that one : HTTPRequest(Type, URL$ [, Data$ [, Options [, EnTetes()]]]) but I don't know what is sent by purebasic.
Is the "post" command sent by HTTPRequest ? Or should I add it to the string "URL$" ?

If anyone has experience in this or an example I'm interested, I'm just starting out with programming Basic and Web language and swimming a bit :lol:

Thank you very much
User avatar
pdwyer
Addict
Addict
Posts: 2813
Joined: Tue May 08, 2007 1:27 pm
Location: Chiba, Japan

Re: How to use online API ?

Post by pdwyer »

I went down this rabbit hole a little but perhaps I'm not the best to give advice as I struggled.

PB has a json lib but I found it quite difficult to use and for simple stuff just stayed with string concatenation manually as it was not intuitive

If you need to use complex json in PB, spend some time with the syntax of the object model and then you can output the string with
ComposeJSON() that will put all the quotes in for you (once you work out what you want to send)

If you need to build manually then you'll be using so many:
mystr.s = #DQUOTE$ + "hello" + #DQUOTE$

that you'll probably create a new constant #DQ$ for less typing :wink:

Normally I wouldn't say this on this forum because I love PB, but do you need to use PB?
Recently I started using API's in Powershell and it was sooooo easy. the API call was easy, the json was easy even for complex nested structures. I would even consider building the powershell text in PB and CMD'ing out as it is so much better. (I've been trying to think of a way to implement something similar in PB)

PB really needs get a new json (and XML) parser that's easier to use and understand. I'm sure I'll get stabbed for mentioning another language and I'm interested to know what others think of the PB JSON lib because I really don't like it. It's better than nothing but not much. Switching language was a better option for me even though I had to bite my tongue as I had been dissing powershell for over a decade :oops:

not sure if this post is of much help though
Paul Dwyer

“In nature, it’s not the strongest nor the most intelligent who survives. It’s the most adaptable to change” - Charles Darwin
“If you can't explain it to a six-year old you really don't understand it yourself.” - Albert Einstein
User avatar
spikey
Enthusiast
Enthusiast
Posts: 771
Joined: Wed Sep 22, 2010 1:17 pm
Location: United Kingdom

Re: How to use online API ?

Post by spikey »

Walko wrote: Mon Oct 17, 2022 11:56 amHow to manage strings with several symbols """" ??
You can use the constant #DQUOTE$ to embed double quotes in strings. You may also need carriage return (#CR$), line feed (#LF$) or carriage return & line feed (#CRLF$) too, depending on whether or not the API 'likes'/'doesn't like' returns (it appears not all APIs are consistent in this).

Code: Select all

Debug #DQUOTE$ + "This string has double quotes." + #DQUOTE$
Debug #DQUOTE$ + #DQUOTE$ + "This string has double double quotes." + #DQUOTE$ + #DQUOTE$
Walko wrote: Mon Oct 17, 2022 11:56 amhow can i generate this command with Purebasic ?
As you suspect you're looking for HTTPRequest.
Walko wrote: Mon Oct 17, 2022 11:56 amIs the "post" command sent by HTTPRequest ? Or should I add it to the string "URL$" ?
No, don't add it to the URL. The instructions 'Type' parameter sets this, you will need to specify #PB_HTTP_Post where the API doc says POST or #PB_HTTP_Get if the API doc says GET.
Walko wrote: Mon Oct 17, 2022 11:56 amI don't know what is sent by purebasic.
PB will prepare a buffer containing the relevant preamble for the request you specify containing the payload that you supply via the Data$ argument and send it to the endpoint specified in the URL$ argument. You will also need a Header$() parameter to specify 'application/json' content:

Code: Select all

NewMap Header$()
Header$("ContentType") = "application/json"
Header$("accept") = "application/json"
Header$("User-Agent") = "Firefox 54.0"
Once you have a response you need to interrogate it with the HTTPInfo instruction before tidying up with FinishHTTP.
This isn't tested (I don't have an API key so I get an error back) but something like:

Code: Select all

Define URL$ = "https://api.mouser.com/api/v1/search/partnumber?apiKey=xxxxxxxxxx"
Debug URL$ 

Define Request$ = "{" + #CRLF$ + 
     "  " + #DQUOTE$ + "SearchByPartRequest" + #DQUOTE$ + ": {" + #CRLF$ + 
     "    " + #DQUOTE$ + "mouserPartNumber" + #DQUOTE$ + ":" + #DQUOTE$ + "STM32F407VET6" + #DQUOTE$ + "," + #CRLF$ + 
     "    " + #DQUOTE$ + "partSearchOptions" + #DQUOTE$ + ": "+ #DQUOTE$ + "string" + 
     "}" + #CRLF$ + 
   "}" + #CRLF$
Debug Request$ 

NewMap Header$()
Header$("ContentType") = "application/json"
Header$("accept") = "application/json"
Header$("User-Agent") = "Firefox 54.0"

Request = HTTPRequest(#PB_HTTP_Post, URL$, Request$, 0, Header$())

Debug HTTPInfo(Request, #PB_HTTP_StatusCode)
ParseJSON(0, HTTPInfo(Request, #PB_HTTP_Response))
Debug ComposeJSON(0, #PB_JSON_PrettyPrint)

FinishHTTP(Request)
Update: I made the response easier to look at.
Last edited by spikey on Mon Oct 17, 2022 4:12 pm, edited 1 time in total.
User avatar
Kiffi
Addict
Addict
Posts: 1504
Joined: Tue Mar 02, 2004 1:20 pm
Location: Amphibios 9

Re: How to use online API ?

Post by Kiffi »

In my opinion, it is more transparent to assemble the JSON with the help of a structure.

Code: Select all

EnableExplicit

Structure sSearchByPartRequest
  mouserPartNumber.s
  partSearchOptions.s
EndStructure

Structure sRequest
  SearchByPartRequest.sSearchByPartRequest
EndStructure

Define myRequest.sRequest

myRequest\SearchByPartRequest\mouserPartNumber = "STM32F407VET6"
myRequest\SearchByPartRequest\partSearchOptions = "string"


If CreateJSON(0)
  InsertJSONStructure(JSONValue(0), @myRequest, sRequest)
  Debug ComposeJSON(0, #PB_JSON_PrettyPrint)
  FreeJSON(0)
EndIf
Hygge
User avatar
spikey
Enthusiast
Enthusiast
Posts: 771
Joined: Wed Sep 22, 2010 1:17 pm
Location: United Kingdom

Re: How to use online API ?

Post by spikey »

Looking at the JSON schema for the API at https://api.mouser.com/api/docs/V1, I think I see a problem with your original example. Did your curl command actually work?
https://api.mouser.com/api/docs/V1 wrote: "Optional. If not provided, the default is None. Refers to options supported by the search engine. Only one value at a time is supported. The following values are valid: None | Exact - can use string representations or integer IDs: 1[None] | 2[Exact]"
This suggests to me that you need to use a value of None, Exact, 1 or 2 but not 'string'.
Walko
User
User
Posts: 11
Joined: Thu Mar 26, 2020 6:08 pm

Re: How to use online API ?

Post by Walko »

Hello,

Thank you all for your answers.

The curl command is generated by the API Documentation demo so It is working well.
I tried it with the command prompt ( Windows ) and I can see the answer from the mouser API.

For the moment I only tried to copy the complete curl command into a string and now I have the exact same thing between the Purebasic string and the curl demo Command.

here are my variables :

Code: Select all

POSTCMD$   = "curl -X POST "
MouserURL$ = "https://api.mouser.com/api/v1/search/partnumber?apiKey="MY_API_KEY""
Misc$ = " -H  " + #DQUOTE$ + "accept: application/json" + #DQUOTE$ + " -H  " + #DQUOTE$ + "Content-Type: application/json" + #DQUOTE$ + " -d " + #DQUOTE$ + "{  \" + #DQUOTE$ + "SearchByPartRequest\" + #DQUOTE$ + ": {    \" + #DQUOTE$ + "mouserPartNumber\" + #DQUOTE$ + ": \" + #DQUOTE$ + "STM32F407VGT6\" + #DQUOTE$ + ",    \" + #DQUOTE$ + "partSearchOptions\" + #DQUOTE$ + ": \" + #DQUOTE$ + "string\" + #DQUOTE$ +  "  }}" + #DQUOTE$  
I tried to send this command with HTTPRequest but it fails ( server response:0 ) :
I tried with and without including POSTCMD$

Code: Select all

;HttpRequest = HTTPRequest(#PB_HTTP_Post,POSTCMD$ +#DQUOTE$ + MouserURL$ + #DQUOTE$ + Misc$)
 HttpRequest = HTTPRequest(#PB_HTTP_Post,#DQUOTE$ + MouserURL$ + #DQUOTE$ + Misc$)
 If HttpRequest
 Debug "Status: " + HTTPInfo(HTTPRequest, #PB_HTTP_StatusCode)
 Debug "Réponse: " + HTTPInfo(HTTPRequest, #PB_HTTP_Response)
Do you know what I am doing wrong ?

Thank you :)
Last edited by Walko on Tue Oct 18, 2022 12:50 pm, edited 1 time in total.
infratec
Always Here
Always Here
Posts: 7620
Joined: Sun Sep 07, 2008 12:45 pm
Location: Germany

Re: How to use online API ?

Post by infratec »

Everything :wink:

curl in your case is an executable. You need RunProgram() to use it.

Here is the PB way:

Code: Select all

EnableExplicit

#API_KEY$ = "YOUR API KEY"


Structure MouserSearchByPart_Structure
  mouserPartNumber.s
  partSearchOptions.s
EndStructure

Structure MouserSearch_Structure
  SearchByPartRequest.MouserSearchByPart_Structure
EndStructure


Structure MouserErroList_Structure
  Id.i
  Code.s
  Message.s
  ResourceKey.s
  ResourceFormatString.s
  ResourceFormatString2.s
  PropertyName.s
EndStructure

Structure MouserProductAttributesList_Structure
  AttributeName.s
  AttributeValue.s
EndStructure

Structure MouserPriceBreaksList_Structure
  Quantity.i
  Price.s
  Currency.s
EndStructure

Structure MouserAlternatePackagingsList_Structure
  APMfrPN.s
EndStructure

Structure MouserInfoMessagesList_Structure
  
EndStructure

Structure MouserProductComplianceList_Structure
  ComplianceName.s
  ComplianceValue.s
EndStructure

Structure MouserPartsList_Structure
  Availability.s
  DataSheetUrl.s
  Description.s
  FactoryStock.s
  ImagePath.s
  Category.s
  LeadTime.s
  LifecycleStatus.s
  Manufacturer.s
  ManufacturerPartNumber.s
  Min.s
  Mult.s
  MouserPartNumber.s
  List ProductAttributes.MouserProductAttributesList_Structure()
  List PriceBreaks.MouserPriceBreaksList_Structure()
  List AlternatePackagings.MouserAlternatePackagingsList_Structure()
  ProductDetailUrl.s
  Reeling.i
  ROHSStatus.s
  SuggestedReplacement.s
  MultiSimBlue.i
  List InfoMessages.MouserInfoMessagesList_Structure()
  List ProductCompliance.MouserProductComplianceList_Structure()
EndStructure

Structure MouserSearchResults_Structure
  NumberOfResult.i
  List Parts.MouserPartsList_Structure()
EndStructure

Structure MouserSearchResult_Structure
  List Errors.MouserErroList_Structure()
  SearchResults.MouserSearchResults_Structure
EndStructure



Procedure.i MouserSearch(*MouserSearch.MouserSearch_Structure, *MouserSearchResult.MouserSearchResult_Structure)
  
  Protected Result.i, HTTPRequest.i, Post$, JSON.i, JSON$
  Protected NewMap Header$()
  
  
  Header$("Content-Type") = "application/json"
  Header$("Accept") = "application/json"
  
  JSON = CreateJSON(#PB_Any)
  If JSON
    InsertJSONStructure(JSONValue(JSON), *MouserSearch, MouserSearch_Structure)
    Post$ = ComposeJSON(JSON)
    ;Debug Post$
    FreeJSON(JSON)
    
    HTTPRequest = HTTPRequest(#PB_HTTP_Post, "https://api.mouser.com/api/v1/search/partnumber?apiKey=" + #API_KEY$, Post$, 0, Header$())
    If HTTPRequest
      JSON$ = HTTPInfo(HTTPRequest, #PB_HTTP_Response)
      ;Debug JSON$
      JSON = ParseJSON(#PB_Any, JSON$)
      If JSON
        ExtractJSONStructure(JSONValue(JSON), *MouserSearchResult, MouserSearchResult_Structure)
        FreeJSON(JSON)
        If ListSize(*MouserSearchResult\Errors()) = 0
          Result = #True
        EndIf
      EndIf
      FinishHTTP(HTTPRequest)
    EndIf
    
  EndIf
  
  ProcedureReturn Result
  
EndProcedure



Define MouserSearch.MouserSearch_Structure
Define MouserSearchResult.MouserSearchResult_Structure

MouserSearch\SearchByPartRequest\mouserPartNumber = "STM32F407VGT6"
MouserSearch\SearchByPartRequest\partSearchOptions = "string"

If MouserSearch(@MouserSearch, @MouserSearchResult)
  Debug "Results: " + Str(MouserSearchResult\SearchResults\NumberOfResult)
  ForEach MouserSearchResult\SearchResults\Parts()
    Debug MouserSearchResult\SearchResults\Parts()\MouserPartNumber + " : " + MouserSearchResult\SearchResults\Parts()\Availability
    ForEach MouserSearchResult\SearchResults\Parts()\PriceBreaks()
      Debug "  " + MouserSearchResult\SearchResults\Parts()\PriceBreaks()\Quantity + " " + MouserSearchResult\SearchResults\Parts()\PriceBreaks()\Price
    Next
  Next
Else
  ForEach MouserSearchResult\Errors()
    Debug MouserSearchResult\Errors()\Message + " : " + MouserSearchResult\Errors()\PropertyName
  Next
EndIf
Walko
User
User
Posts: 11
Joined: Thu Mar 26, 2020 6:08 pm

Re: How to use online API ?

Post by Walko »

infratec :shock:

It's working very well 8)

Thank you very much, I didn't ask for so much!
I will study your program because I am not familiar with list and structures.
This is a very good exercise with something real and usefull for me to learn.

Thank you again for your time.
Post Reply