Android Question call api rest problem

hookshy

Well-Known Member
Licensed User
Longtime User
I have problems understanding how to build a http post to acces an api service
I tried using the clarifai api and I make an example , unfortunately I do not understand how it works and how to create proper http statement starting from their documentation

here is my example
B4X:
#Region  Project Attributes
    #ApplicationLabel: B4A Example
    #VersionCode: 1
    #VersionName:
    'SupportedOrientations possible values: unspecified, landscape or portrait.
    #SupportedOrientations: unspecified
    #CanInstallToExternalStorage: False
#End Region

#Region  Activity Attributes
    #FullScreen: False
    #IncludeTitle: True
    #BridgeLogger: True
  
#End Region

Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.

End Sub

Sub Globals
    'These global variables will be redeclared each time the activity is created.
    'These variables can only be accessed from this module.

End Sub

Sub Activity_Create(FirstTime As Boolean)
    'Do not forget to load the layout file created with the visual designer. For example:
    'Activity.LoadLayout("Layout1")




End Sub

Sub Activity_Resume
  
'original content 
'    curl -X POST \
'    -H "Authorization: Key YOUR_API_KEY" \
'    -H "Content-Type: application/json" \
'    -d '
'  {
'    "inputs": [
'    {
'    "data": {
'    "image": {
'    "url": "https://samples.clarifai.com/metro-north.jpg"
'    }
'        }
'      }
'    ]
'  }'\
'    https://api.clarifai.com/v2/models/aaa03c23b3724a16a56b629203edc62c/outputs
  
  
    Dim job As HttpJob
    job.Initialize("myfirstapi",Me)
    job.PostString("https://api.clarifai.com/v2/models/aaa03c23b3724a16a56b629203edc62c/outputs",$"'{
    "inputs": [
    {
    "data": {
    "image": {
    "url": "https://samples.clarifai.com/metro-north.jpg"
    }
        }
      }
    ]
  }'\"$)
    job.GetRequest.SetHeader("Authorization: Key", "YOUR_API_KEY_replaced with my api key")
    'job.GetRequest.SetHeader("Content-Type", "application/json")
    job.GetRequest.SetContentType("application/json")
    job.GetRequest.SetContentEncoding("text/plain")
  
  
End Sub

Sub Activity_Pause (UserClosed As Boolean)

End Sub
 
Sub JobDone(Job As HttpJob)

    Select Job.JobName
  
        Case "myfirstapi"
            Log("found a http job:"&Job.Success)
          
            If Job.Success Then
              
                Dim res As String
                res = Job.GetString
                Dim parser As JSONParser
                parser.Initialize(res)
              
                Dim ListOfPO As List
                ListOfPO = parser.NextArray
              
                For i=0 To ListOfPO.Size-1
                    Log(ListOfPO.Get(i))
                Next
              
                                  
            End If
  
    End Select




End Sub


Error I got:
hc_response error{"status":{"code":11001,"description":"Invalid authentication token","details":"Invalid Authorization Header"},"outputs":[]}


Thank you
 
Last edited:

hookshy

Well-Known Member
Licensed User
Longtime User
I have changed a small : ' updated the first post
now another error i have:
hc_response error{"status":{"code":11102,"description":"Invalid request","details":"Malformed or invalid request"}}
 
Upvote 0

DonManfred

Expert
Licensed User
Longtime User
My first thought:
Are you sure the model is YOUR model which you are trying to update?
aaa03c23b3724a16a56b629203edc62c looks like the model id from the Documentation

Try to ADD a Model first. Then use the new model id to put an image there.

https://clarifai.com/developer/guide/models#models
 
Upvote 0

DonManfred

Expert
Licensed User
Longtime User
B4X:
Sub Activity_Resume
    Dim job As HttpJob
    job.Initialize("myfirstapi",Me)
    job.Download("https://api.clarifai.com/v2/models")
    job.GetRequest.SetHeader("Authorization", "Key [your api key]") ' <--- !!!
    job.GetRequest.SetContentEncoding("text/plain")
End Sub
Sub JobDone(Job As HttpJob)

    Select Job.JobName
 
        Case "myfirstapi"
            Log("found a http job:"&Job.Success)
          
            If Job.Success Then
              
                Dim res As String
                res = Job.GetString
                Log(res)
                Dim out1 As OutputStream = File.OpenOutput(File.DirDefaultExternal, "Clarifi-JSON.txt",False )
                File.Copy2(Job.GetInputStream, out1)
                out1.Close
                Dim parser As JSONParser
                parser.Initialize(res)
              
                Dim parser As JSONParser
                parser.Initialize(res)
                Dim root As Map = parser.NextObject
                Log(root)
                Dim models As List = root.Get("models")
                Log(models)
            End If
 
    End Select
    Job.Release
End Sub
 
Upvote 0

hookshy

Well-Known Member
Licensed User
Longtime User
Thank you DonManfred

I try to understand how this model works and found this explanatory :
The type of prediction is based on what model you run the input through. For example, if you run your input through the 'food' model, the predictions it returns will contain concepts that the 'food' model knows about. If you run your input through the 'color' model, it will return predictions about the dominant colors in your image.

I have model general inside of my project ...so if model general is used it could return some results
I have updated the code above with my model id "General" is the word that it returns when using their copy option


Q: Where do I put my picture url so that the service can take a look at it and return any results ?
Code can be tested with my autorisation key and model name (will ask to clarifai suport what if this General is active and how it works)

Here is how account and project looks like : http://danken.ro/pub/clarifai.bmp

hc_response error{"status":{"code":11103,"description":"Method not allowed","details":"Method Not Allowed"}}
B4X:
Sub Activity_Resume
    Dim job As HttpJob
    job.Initialize("myfirstapi",Me)
    job.Download("https://api.clarifai.com/v2/models/General/outputs")
    job.GetRequest.SetHeader("Authorization", "Key [36361a16c25c4fc98ff3a7b26276bbb3]") ' <--- !!!
    job.GetRequest.SetContentEncoding("text/plain")
End Sub
Sub JobDone(Job As HttpJob)

    Select Job.JobName
 
        Case "myfirstapi"
            Log("found a http job:"&Job.Success)
      
            If Job.Success Then
          
                Dim res As String
                res = Job.GetString
                Log(res)
                Dim out1 As OutputStream = File.OpenOutput(File.DirDefaultExternal, "Clarifi-JSON.txt",False )
                File.Copy2(Job.GetInputStream, out1)
                out1.Close
                Dim parser As JSONParser
                parser.Initialize(res)
          
                Dim parser As JSONParser
                parser.Initialize(res)
                Dim root As Map = parser.NextObject
                Log(root)
                Dim models As List = root.Get("models")
                Log(models)
            End If
 
    End Select
    Job.Release
End Sub

clarifai.bmp
 
Last edited:
Upvote 0

hookshy

Well-Known Member
Licensed User
Longtime User
Found out where to insert images to create a model ....you can add new pictures to your model , but yet when using a food model ...i it can return some results when sending a banana picture.
Still wondering how I am going to send the link of the picture to be compared

I wish I could make this work
 
Last edited:
Upvote 0

DonManfred

Expert
Licensed User
Longtime User
Found out where to insert images to create a model ....you can add new pictures to your model , but yet when using a food model ...i it can return some results when sending a banana picture.
Still wondering how I am going to send the link of the picture to be compared
i´m not sure that i understand (english is not my native language).

I used the Food model and let it use an own picture i made with my device and uploaded the Pic to an Onlineserver beforehand.

B4X:
    Dim m As Map
    m.Initialize   
    Dim urlmap As Map
    urlmap.Initialize
    urlmap.Put("url","http://cast.basic4android.de/WhatsApp.jpeg")
    Dim datamap As Map
    datamap.Initialize
    datamap.Put("image",urlmap)
    Dim m2 As Map
    m2.Initialize
    m2.Put("data",datamap)
    Dim l As List
    l.Initialize
    l.Add(m2)
    m.Put("inputs",l)
    Dim jsongen As JSONGenerator
    jsongen.Initialize(m)
    Log(jsongen.ToString)
    Dim job As HttpJob
    job.Initialize("foodtest",Me)
    job.PostString("https://api.clarifai.com/v2/models/bd367be194cf45149e75f01d59f77ba7/outputs", jsongen.ToString)
    job.GetRequest.SetHeader("Authorization", "Key xxx") ' key replaced by xxx
    job.GetRequest.SetContentEncoding("text/plain")

B4X:
Sub JobDone(Job As HttpJob)
    Log("JobDone("&Job.JobName&")")
    Select Job.JobName
        Case "foodtest"
            Log("foodtest job:"&Job.Success)
            If Job.Success Then
                Dim res As String
                res = Job.GetString
                Log(res)
            Else
                Dim res As String
                res = Job.ErrorMessage
                Log(res)
            End If
            Dim out1 As OutputStream = File.OpenOutput(File.DirDefaultExternal, "Clarifi-JSON-foodtest.txt",False )
            File.Copy2(Job.GetInputStream, out1)
            out1.Close
    End Select
    Job.Release
End Sub

{"status":{"code":10000,"description":"Ok"},"outputs":[{"id":"2bd79f4dc88e43639adf9119ec22923b","status":{"code":10000,"description":"Ok"},"created_at":"2018-10-12T13:14:26.340924211Z","model":{"id":"bd367be194cf45149e75f01d59f77ba7","name":"food-items-v1.0","created_at":"2016-09-17T22:18:59.955626Z","app_id":"main","output_info":{"message":"Show output_info with: GET /models/{model_id}/output_info","type":"concept","type_ext":"concept"},"model_version":{"id":"dfebc169854e429086aceb8368662641","created_at":"2016-09-17T22:18:59.955626Z","status":{"code":21100,"description":"Model trained successfully"}},"display_name":"Food"},"input":{"id":"18d6e195afbd4fddb86399e2c078f619","data":{"image":{"url":"http://cast.basic4android.de/WhatsApp.jpeg"}}},"data":{"concepts":[{"id":"ai_r2Fbdv8L","name":"beer","value":0.9898404,"app_id":"main"},{"id":"ai_JqQgCCL9","name":"ale","value":0.9092907,"app_id":"main"},{"id":"ai_f1zKlGnc","name":"coffee","value":0.90804744,"app_id":"main"},{"id":"ai_CFS37srh","name":"tea","value":0.9077668,"app_id":"main"},{"id":"ai_mZHVM5R0","name":"beans","value":0.7707644,"app_id":"main"},{"id":"ai_skxkRfDl","name":"cake","value":0.7514266,"app_id":"main"},{"id":"ai_vGpGP5X8","name":"stout","value":0.73177123,"app_id":"main"},{"id":"ai_DlGsqbPZ","name":"chocolate","value":0.67409194,"app_id":"main"},{"id":"ai_fZsLlGwm","name":"pizza","value":0.6730238,"app_id":"main"},{"id":"ai_j16nh7nz","name":"soda","value":0.6536692,"app_id":"main"},{"id":"ai_kTsPMX36","name":"wine","value":0.6441758,"app_id":"main"},{"id":"ai_jmcSl8c1","name":"bacon","value":0.6252506,"app_id":"main"},{"id":"ai_330XH2RR","name":"lemonade","value":0.574896,"app_id":"main"},{"id":"ai_0wh0dJkQ","name":"sweet","value":0.5222565,"app_id":"main"},{"id":"ai_jvVxlhLh","name":"chicken","value":0.50694597,"app_id":"main"},{"id":"ai_dnsXtXST","name":"coke","value":0.4613104,"app_id":"main"},{"id":"ai_RzcvCV23","name":"ice","value":0.4590909,"app_id":"main"},{"id":"ai_r59dFMqd","name":"juice","value":0.45688766,"app_id":"main"},{"id":"ai_lfPcbVfQ","name":"gem","value":0.43770486,"app_id":"main"},{"id":"ai_T851HmVS","name":"orange","value":0.43727827,"app_id":"main"}]}}]}
 
Upvote 0

DonManfred

Expert
Licensed User
Longtime User
Q: Where do I put my picture url so that the service can take a look at it and return any results ?
See Post #4 (above this one). It is using my picture which i uploaded to my webspace beforehand and i am using the Imageurl to give it to clarifai and i get results for the parsing successfully.
Hope it helps.

If you have another Issue; please create a new thread for any new issue.
 
Upvote 0

DonManfred

Expert
Licensed User
Longtime User
I have updated the code above with my model id "General" is the word that it returns when using their copy option
https://clarifai.com/models/general-image-recognition-model-aaa03c23b3724a16a56b629203edc62c
Info
MODEL NAME
General

OWNER
Clarifai

MODEL ID
aaa03c23b3724a16a56b629203edc62c

CONCEPTS
Afternoon, Art, Beautiful, Bicycle, Happiness, Togetherness and more

"aaa03c23b3724a16a56b629203edc62c" is the modelid you need to use; not "General"

So the code should be

B4X:
    Dim m As Map
    m.Initialize   
    Dim urlmap As Map
    urlmap.Initialize
    urlmap.Put("url","http://cast.basic4android.de/xxxxx.jpeg") ' real imagename changed....
    Dim datamap As Map
    datamap.Initialize
    datamap.Put("image",urlmap)
    Dim m2 As Map
    m2.Initialize
    m2.Put("data",datamap)
    Dim l As List
    l.Initialize
    l.Add(m2)
    m.Put("inputs",l)
    Dim jsongen As JSONGenerator
    jsongen.Initialize(m)
    Log(jsongen.ToString)
    Dim job As HttpJob
    job.Initialize("general",Me)
    job.PostString("https://api.clarifai.com/v2/models/aaa03c23b3724a16a56b629203edc62c/outputs", jsongen.ToString)
    job.GetRequest.SetHeader("Authorization", "Key xxx")
    job.GetRequest.SetContentEncoding("text/plain")


.
 
Upvote 0

hookshy

Well-Known Member
Licensed User
Longtime User
Excellent DonManfred for time and efforts , pushed your donate buttton !


RESULT FROM LOG FILE
B4X:
{"status":{"code":10000,"description":"Ok"},"outputs":[{"id":"c917068bfea8424c993c067e7229d4ce","status":{"code":10000,"description":"Ok"},"created_at":"2018-10-13T04:20:04.865171189Z","model":{"id":"aaa03c23b3724a16a56b629203edc62c","name":"general-v1.3","created_at":"2016-03-09T17:11:39.608845Z","app_id":"main","output_info":{"message":"Show output_info with: GET /models/{model_id}/output_info","type":"concept","type_ext":"concept"},"model_version":{"id":"aa9ca48295b37401f8af92ad1af0d91d","created_at":"2016-07-13T01:19:12.147644Z","status":{"code":21100,"description":"Model trained successfully"}},"display_name":"General"},"input":{"id":"6b345e672a15401f92da2f7c803ee18a","data":{"image":{"url":"http://cast.basic4android.de/WhatsApp.jpeg"}}},"data":{"concepts":[{"id":"ai_TBlp0Pt3","name":"beer","value":0.9858302,"app_id":"main"},{"id":"ai_786Zr311","name":"no person","value":0.9673026,"app_id":"main"},{"id":"ai_3PlgVmlN","name":"food","value":0.92680633,"app_id":"main"},{"id":"ai_zJx6RbxW","name":"drink","value":0.9178269,"app_id":"main"},{"id":"ai_7WNVdPhm","name":"competition","value":0.90863574,"app_id":"main"},{"id":"ai_mXT38hpL","name":"football","value":0.88462114,"app_id":"main"},{"id":"ai_6lhccv44","name":"business","value":0.8663223,"app_id":"main"},{"id":"ai_1QnrJLVf","name":"cola","value":0.86524355,"app_id":"main"},{"id":"ai_fKppxwrj","name":"soccer","value":0.8502575,"app_id":"main"},{"id":"ai_BrnHNkt0","name":"coffee","value":0.8434862,"app_id":"main"},{"id":"ai_k9gQdGrS","name":"logo","value":0.8287163,"app_id":"main"},{"id":"ai_mCpQg89c","name":"glass","value":0.8283142,"app_id":"main"},{"id":"ai_bBXFkGB1","name":"auto racing","value":0.81631154,"app_id":"main"},{"id":"ai_TkWkj1sX","name":"container","value":0.78269684,"app_id":"main"},{"id":"ai_qRLHzCTT","name":"editorial","value":0.74693507,"app_id":"main"},{"id":"ai_Pf2b7clG","name":"indoors","value":0.7429966,"app_id":"main"},{"id":"ai_ggQlMG6W","name":"industry","value":0.71813667,"app_id":"main"},{"id":"ai_Smd3xNdn","name":"healthcare","value":0.704988,"app_id":"main"},{"id":"ai_mZ2tl6cW","name":"health","value":0.70487773,"app_id":"main"},{"id":"ai_2D3NBTV7","name":"championship","value":0.70235485,"app_id":"main"}]}}]}

RUNNING CODE

B4X:
#Region  Project Attributes
    #ApplicationLabel: B4A Example
    #VersionCode: 1
    #VersionName:
    'SupportedOrientations possible values: unspecified, landscape or portrait.
    #SupportedOrientations: unspecified
    #CanInstallToExternalStorage: False
#End Region

#Region  Activity Attributes
    #FullScreen: False
    #IncludeTitle: True
    #BridgeLogger: True
    
#End Region

Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.

End Sub

Sub Globals
    'These global variables will be redeclared each time the activity is created.
    'These variables can only be accessed from this module.

End Sub

Sub Activity_Create(FirstTime As Boolean)
    'Do not forget to load the layout file created with the visual designer. For example:
    'Activity.LoadLayout("Layout1")
End Sub


Sub Activity_Pause (UserClosed As Boolean)

End Sub
 

Sub Activity_Resume
        
    Dim m As Map
    m.Initialize
    Dim urlmap As Map
    urlmap.Initialize
    urlmap.Put("url","http://cast.basic4android.de/WhatsApp.jpeg") ' real imagename changed....
    Dim datamap As Map
    datamap.Initialize
    datamap.Put("image",urlmap)
    Dim m2 As Map
    m2.Initialize
    m2.Put("data",datamap)
    Dim l As List
    l.Initialize
    l.Add(m2)
    m.Put("inputs",l)
    Dim jsongen As JSONGenerator
    jsongen.Initialize(m)
    Log(jsongen.ToString)
    Dim job As HttpJob
    job.Initialize("general",Me)
    job.PostString("https://api.clarifai.com/v2/models/aaa03c23b3724a16a56b629203edc62c/outputs", jsongen.ToString)
    job.GetRequest.SetHeader("Authorization", "Key 36361a16c25c4fc98ff3a7b26276bbb3")'my app key from clarifai.com
    job.GetRequest.SetContentEncoding("text/plain")
    
End Sub
Sub JobDone(Job As HttpJob)
    Log("JobDone("&Job.JobName&")")
    Select Job.JobName
        Case "general"
            Log("general:"&Job.Success)
            If Job.Success Then
                Dim res As String
                res = Job.GetString
                Log(res)
                        
            Else
                Dim res As String
                res = Job.ErrorMessage
                Log(res)
            End If
            
            
            Dim out1 As OutputStream = File.OpenOutput(File.DirInternal, "Clarifi-JSON-foodtest.txt",False )
            File.Copy2(Job.GetInputStream, out1)
            out1.Close
            
            
    End Select
    Job.Release
End Sub
 
Upvote 0
Top