Does anyone (#TimHall) have suggestions on how to make a GET JSON request to a webservice using VBA-WEB in MS Access with a cURL string? I have reviewed many samples including these: Equivalent cURL in VBA? ; Using Excel to pull data from API ; and more. The cURL is this:
curl -XGET -H "Authorization: Bearer [oauth_token]" -H "Content-Type: application/hal+json" https://api.somewebsite.com/api/my/orders/selling/all?updated_start_date=2015-01-01T12:00-00:00&updated_end_date=2015-01-02T12:00-00:00
My end goal is to "get" the json and then save it to a .txt file on a local drive for use with JsonConverter.ParseJson.
Per #QHall suggestion, here is my best attempt- revised, based on this : https://vba-tools.github.io/VBA-Web/docs/ "GetJSON" section.
Private Sub GetTheOrdersJson()
Dim Client As New WebClient
Dim Url As String
Url = "https://api.somewebsite.com/api/my/orders/selling/all"
Dim Response As WebResponse
Set Response = Client.GetJson(Url)
Dim Headers As New Collection
Headers.Add WebHelpers.CreateKeyValue("Authorization", "Bearer [1234567890]")
Dim Options As New Dictionary
Options.Add "Headers", Headers
Set Response = Client.GetJson(Url, Options)
End Sub
In the Immediate Window this prints:
ERROR - WebHelpers.ParseByFormat: 11000, An error occurred during parsing
10001: Error parsing JSON:
Please set
^
Expecting '{' or '['
ERROR - WebHelpers.ParseByFormat: 11000, An error occurred during parsing
10001: Error parsing JSON:
Please set
^
Expecting '{' or '['
ERROR - WebHelpers.ParseByFormat: 11000, An error occurred during parsing
10001: Error parsing JSON:
Por favor e
^
Expecting '{' or '['
ERROR - WebHelpers.ParseByFormat: 11000, An error occurred during parsing
10001: Error parsing JSON:
Por favor e
^
Expecting '{' or '['
Related
POST request without body parameter gives a JSON parse error. Mentioned the error below.
API Call
api.post('notification/seen')
Error:
{"message":{"name":"SyntaxError","msg":"Unexpected token n in JSON at position 0","stack":"SyntaxError: Unexpected token n in JSON at position 0\n at JSON.parse ()\n at createStrictSyntaxError (/app/node_modules/body-parser/lib/types/json.js:158:10)\n at parse (/app/node_modules/body-parser/lib/types/json.js:83:15)\n at /app/node_modules/body-parser/lib/read.js:121:18\n at invokeCallback (/app/node_modules/raw-body/index.js:224:16)\n at done (/app/node_modules/raw-body/index.js:213:7)\n at IncomingMessage.onEnd (/app/node_modules/raw-body/index.js:273:7)\n at IncomingMessage.emit (events.js:327:22)\n at IncomingMessage.EventEmitter.emit (domain.js:486:12)\n at endReadableNT (_stream_readable.js:1327:12)\n at processTicksAndRejections (internal/process/task_queues.js:80:21)"},"level":"error","timestamp":"2021-09-28T06:29:19.577Z"}
Swagger API structure
/notification/seen:
post:
tags:
- Notification
responses:
204:
description: Update Seen Notification Success
401:
description: Access Token Missing/Expired
500:
description: Something went wrong!
If same API I call with adding dummy body as below with changing the Swagger API structure I am not getting the error.
API Call
api.post('notification/seen',{id:"data"})
Swagger API structure
/notification/seen:
post:
tags:
- Notification
parameters:
- in: body
name: body
schema:
type: object
responses:
204:
description: Update Seen Notification Success
401:
description: Access Token Missing/Expired
500:
description: Something went wrong!
And also if I change POST to GET request then also I am not getting the error.
How to fix the error with the POST request without a body parameter?
I am using aspx vb .net to connect with instagram api
I am using the following link as references: https://code.msdn.microsoft.com/Haroon-Said-e1d8d388
ERROR: The remote server returned an error: (400) Bad Request.
It is weird becuase i followed all steps and imported json as showed in above link. any idea? below is my code:
Dim json As String = ""
Try
Dim parameters As New NameValueCollection
parameters.Add("client_id", Client_ID)
parameters.Add("client_secret", ClientSecret)
parameters.Add("grant_type", "authorization_code")
parameters.Add("redirect_uri", Redirect_URI)
parameters.Add("code", Code)
Dim client As WebClient = New WebClient()
Try
'ERROR HERE
Dim result = client.UploadValues("https://api.instagram.com/oauth/access_token", "POST", parameters)
...
Catch ex As Exception
labelTest.Text += "---" & ex.Message
End Try
Thanks. yeah I been working on this for couple months now and trying to debug but I just have no idea whats going on. I mean I looked at insta api webbsite sill no luck. I tested my values also and they seem to be correct:
curl -F 'client_id=CLIENT_ID' \
-F 'client_secret=CLIENT_SECRET' \
-F 'grant_type=authorization_code' \
-F 'redirect_uri=AUTHORIZATION_REDIRECT_URI' \
-F 'code=CODE' \
https://api.instagram.com/oauth/access_token
client_secret = f208d9fc9cec4b69bdd5f8f1386a
client_secret = d836619eede4490fd12983b95961
grant_type = authorization_code
redirect_uri = http://localhost:1861/UI/Home.aspx
code = 6185508825da0c28a33ac5dcc77
note, 'code' i am getting when when user logs into insta. I used the following url to get the code:
https://api.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=code
I know authorize is correct becuase it gives me code in url
solved!
just changed response_type from code to token... it will give you access_token
I have a curl request with is giving expected output :
curl -H "Authorization: Token 519dde16245438025cccb526bxxx9f3e8ce88289" --form "user=47" --form "language=HI" --form "audio_file=#/home/rishabh/Desktop/liv/audio_1.wav" --form "transcribe=1" https://dev.liv.ai/liv_speech_api/recordings/
But when I do the same using python script I am getting error
Please see the code below :
def get_app_session_id():
headers = {'Authorization' : 'Token 519dde16245438025cccb526bdxxxx3e8ce88289'}
data = {'user' : '47', 'language' : 'HI', 'transcribe':'1'}
files = {'audio_file' : open('audio_1.wav')}
url = 'https://dev.liv.ai/liv_speech_api/recordings/'
res = requests.post(url, headers = headers
, data = data, files = files)
return res
Let me know how to resolve this issue
201 means : The request has been fulfilled, resulting in the creation of a new resource
I'm trying to translate the following cURL command that extrats a .diff content in GitHub to VB:
curl -H 'Authorization: token myGitHubToken' -H "Accept: application/vnd.github.v3.diff" https://api.github.com/repos/[USR]/[REPO]/commits/[COMMITID]
The cURL works fine. And my code in VB with HttpWebRequest is
Dim url As New Uri("https://api.github.com/repos/[USR]/[REPO]/commits/[COMMITID]")
Dim myReq As HttpWebRequest = HttpWebRequest.Create(url)
SetAllowUnsafeHeaderParsing20()
myReq.Headers.Add("Authorization: token myGitHubToken")
myReq.Accept("application/vnd.github.v3.diff")
myReq.KeepAlive = False
Dim response As HttpWebResponse = CType(myReq.GetResponse(), HttpWebResponse)
But in GetResponse, throws me a WebException :
"The remote server returned an error: (403) Forbidden"
Is ok my traslation? There is something wrong?
I'm writing a web API that has a post method accepting files uploaded from UI.
public async Task<List<string>> PostAsync()
{
if (Request.Content.IsMimeMultipartContent("form-data"))
{
string uploadPath = HttpContext.Current.Server.MapPath("~/uploads");
var streamProvider = new MyStreamProvider(uploadPath);
await Request.Content.ReadAsMultipartAsync(streamProvider);
return streamProvider.FileData
.Select(file => new FileInfo(file.LocalFileName))
.Select(fi => "File uploaded as " + fi.FullName + " (" + fi.Length + " bytes)")
.ToList();
}
else
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.BadRequest, "Invalid Request!");
throw new HttpResponseException(response);
}
}
Then I post a request for the above action by postman.
I set the content-type header to multipart/form-data
but an error occurred during the execution of action.
here is the error message body :
"Invalid 'HttpContent' instance provided. It does not have a 'multipart' content-type header with a 'boundary' parameter.\r\nParameter name: content"
I went to the postman headers but I found that the request header content type was set to application-json.
You are looking on the response header which is json format and this is ok for you.
Your real problem is with the postman request, so just remove the 'Content-Type: multipart/form-data' entry from request header.
It's enough to upload a file as form-data and send the request.
Look what happen when you set the Content-Type manually vs. when you not:
Postman knows to set both the content type and boundary, since you set only the content type
First: Postman have a bug in handling file-based requests.
You can try adding this to your WebApiConfig.cs it worked for me:
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();