App Inventor has a component called Web which gives you the functionality to send and fetch data from a server or a website through GET and POST requests. This component can decode both JSON and HTML formatted data. We will be writing an app called iRead that will ask a user to type in a full or partial book name and query Google’s database of books using Books API and retrieve the most relevant book info. We will parse the Title and Author of the book, we will get the image URL of the book cover, and finally the book URL which can be launched through a browser. This is how our app would look like-
Before we start, I advise you to read on anything that is unfamiliar to you but mentioned in the paragraph above like Books API, JSON, HTML, GET, POST, etc.
First thing first, build your user interface (UI) in the Designer window. Mine looks like this-
As you can see I renamed default names of components App Inventor provides. It’s upto you what you want to name the components you use. If you are having hard time designing the UI, download the source file iRead and take a look. What matters is that you have all the essential components as shown in the UI screenshot above.
Have you tried executing a Book API query request yet? Click on the link below to see the API response.
https://www.googleapis.com/books/v1/volumes?q=Harry&maxResults=1&projection=lite This gives you a response that looks similar to this-
Our concern is not the actual book info (Over time you might not get the same book info using the same query), our concerns are the tokens that we’ll need to identify and parse specific data. Take a look at the tokens like “title”: that ends with a comma and a new line, “authors”: that ends with ], etc.
Now let’s start defining actions and interactions in the blocks editor.
We have three global variables defined-
googleBookSearchURL – That’s where we store the API URL address for book search.
tempData – We will use that for saving temporary data.
bookURL – That’s where we will parse and store the URL (“infoLink” token) of the book info returned by the API.
When a user enters a book name and hits Search button, we call GetBookInfo procedure where we simply construct our URL with user inputted text and encode it for using it as a URL, and finally feed it to Web component’s Url property. We want to get only one book info (API may return many); so we used maxResults=1. If we didn’t use projection=lite, we would get a lot of other info that we are not going to use in this tutorial app. At the end we call Web.get to execute our query.
How do we know when the server returns a response to our query? Well, we use GotText block of Web component for this. Whenever our app receives something, GotText block will automatically wake up for us to validate and process the data. Let’s parse the JSON response from the API that we receive.
We only can proceed if responseCode is 200 which means our query didn’t fail along the way. We have another procedure called ParseBookResult that actually parses the response. Let’s take a look at it-
In the ParseBookResult procedure, we split the response content using the start tag and end tag. For an example, to parse title of the book, we need to know the beginning and the ending tags of a title. If you have noticed in the query, it returns-
"title": "Harry Potter and the chamber of secrets", "authors": [ "J. K. Rowling" ],
So we know, it begins with “title”: and ends with a comma followed by a new line. That is why we used those tags when we called ParseBookResult from GotText procedure above. In our example raw data, the value is “Harry potter and the chamber of secrets”. Then we decode the JSON value by calling Web’s JsonTextDecode. And finally decode the HTML characters by calling HtmlTextDecode. We call HtmlTextDecode to replace unreadable HTML characters with readable characters. For instance, & is actually & and we want to show & instead of &.
When a user taps on the Read button, we simply launch the browser with the book URL.
For launching a browser, we use ActivityStarter component. We set the action first. You can see a list of actions in this page. We also set the URL we retrieved. Then we just call the StartActivity of ActivityStarter component to launch the browser with the specified URL.
If our bookURL doesn’t contain a valid URL, we simply inform the users.
Download the source file of this app iRead.
Parsing Multiple Results
What if you want to parse multiple results? Well, in that case you define a higher maxResults when you query like this-
As you can see in the screenshot above, we defined maxResults to be three meaning we want three results. If Google cannot find three matches for our book query, in that case we wouldn’t be receiving three results obviously. But if it does find three or more matches for our query, we will receive three.
For demonstration purpose, we will only parse the titles. Maybe you already guessed, we would need for each block to do the job. If you are not familiar with for each, read this tutorial first.
We created a procedure called GetAllTitles that has three arguments –apiResponse, start, and end. We call this procedure with data like this-
As you can see, we passed the responseContent, start and end tags like we did before for parsing a single title. GetAllTitles uses a for each loop and go through all the titles and do the same for parsing, exactly the way we did before. Before we didn’t have the for each loop as we had only one title to parse and now we have a loop because we have many to parse. Note that GetAllTitles procedure stores the result after parsing each title to a global variable named allTitles and returns it.
We used a Label component named OtherTitlesLabel to display the result that is returned by the GetAllTitles procedure. Our app now looks like this-
We created two apps. iRead for single result and iRead2 for multiple. You can download both apps – iRead and iRead2.
How do I use parse on HTML document?
Before you used call ParseBookResult.
Please advise
You can use HtmlTextDecode.
Sajal, pardon this late inquiry as I am just joining the community. Thanks for the beautiful tut. However, how can I display the results as a pair of photo, author, title from these multiple results? This will imply a dynamic creation of the layout elements (label, image, and arrangements. Pulling other titles into one lable is understood but what will be most useful is displaying similar data for each result of the responseContent. Thanks for yout help
The best would be if you only show 1 at a time. If you have a next button, then parse the next list item (last read index + 1) and show. If you want to show mutiple, you need to decide first how many at a time you want to display, because you need to have all necessary elements (e.g. image/labels) available. In app inventor, you cannot dynamically add components.
Thanks Sanjay. I have tried to adopt and extend your tut to my situation of pulling hotels in a city picked from a list picker. For some reason, I am not getting the desired results from extracting the responseContent using specified tags. Can you please check out the detail at this url under user (Obisi7). Ii appreciate you a bunch and the hep to our community. https://community.thunkable.com/t/json-response-to-listpicker/1990/10
Thanks Sir
I am having this new issue (details of which can be found at this forum url: https://community.thunkable.com/t/json-response-to-listpicker/1990/10
Thanks for your help
please create a tutorial using json and the output will be like this
http://i60.tinypic.com/fmnadu.jpg
Gracias por compartir información
Hi,
I am creating an app that shows some of the information from my webpage. How can I use the above method to read and then display particular content from a webpage..?
In the last example, there is a variable that is referenced with no previous mention and was not defined. The variable is named: ‘isfirstItem’. What should that variable be defined as?
You do not define a variable with a type in app inventor. So it doesn’t matter what you initially store there. Also you can download the completed projects and look.
Hello Sajal, you have created a very good App called “JSON Response On App Inventor”. But I need to know how can I read a text (html text) from a website and use this text in app inventor. Can you please show us how to build this app via app inventor. Many thanks in advance. Best regards Sascha
Hi..i want to make an app that displays the result of students from my university website.All one needs to submit is Roll no of the student.The problem is that they are using php to get the roll number and return a pdf file.I want to know how can i use the Web GET to get the required file and display using activity starter.
Thank You.
You should look at this – http://puravidaapps.com/save.php
Thank you so much
how can i make an app in app inventor 2 which can shorten urls using goo.gl ur shortener api
Read this-
http://stackoverflow.com/questions/742013/how-to-code-a-url-shortener
I can’t get this to decode json..
I get a JSON parse error. My returned text is in the format:
{“events”:[{“event”:{“Open_All_Year”:”0″,”Category”:”Default”,”EventID”:”59461″,”Title”:”Beginners’ Birding”
etc
Do you have an example for JSON?
merhaba yazılarınızı okudum anlayama çalıştım ama olmadı amacım http://www.restroomgames.com/blog.php?ID=8 gibi yapmak ve facebook giriş sayfasına text veri almak göndermek butona basmak istiyorum ama olmuyor lütfen .aia örnek nasıl htlm kodları ayıpı okumak degişkenleri appinvertör yazmak nasıl mantık
I tried google translate to translate your post but it’s so vague that I am not sure what exactly you are asking.
How can i create an app in pp inventor which allows me to store data in my online server. As in, I have an online server in Carriots and I want my data to be stored in that, how do i do that. Is it possible using JSON API key? If yes then can you guide me how
Perhaps this will help – http://puravidaapps.com/mysql.php
hı Sajal Dutta I do not know English Waiting for answers
1- http://puravidaapps.com/pubnub.php I want to do this
2- my site this http://www.yarasa.somee.com/ simple chat(.asp)
3- I took the data with the object wep1
4-I have problems sending data
5-A simple example of sending data
First, build a server side service utilizing REST. See http://www.restapitutorial.com/. After that you can build the communication between your AI app and your server.
1-Thanks for the answer
2-this example see http://restroomgames.com/blog.php?ID=8
3-OK retrieve data
4- Looking at this example how to send data
5-Waiting for help
I want to create a splash screen in app inventor.. Is it possible? Pls tell me how to do it or any tutorial?
Just create a screen with whatever you want. Have a clock set to say 3000 ms (3 seconds). When clock fires, show the next screen.
hello, I like the tutorial very much! But in the booknametextbox you only wrote one word, will it still work if I write “The Alchemist” with the space in the middle?
Yes, it will work.
hey, nice tutorial, but actually I using this url https://www.googleapis.com/books/v1/volumes?q=isbn:
and using isbn numbers instead but when I run my application it says it cant decode the json text. it says
” error 1105 unable to decode json text
{
“kind”: “books#volumes”,
“totalItems”: 1,
“items”: [
{
“kind”: “books#volume”,
“id”: “Ta-XAAAACAAJ”,
“etag”: “Z6QGrwMX7Qc”,
“selfLink”: “https://www.googleapis.com/books/v1/volumes/Ta-XAAAACAAJ”,
“volumeInfo”: {
can you please help me?
hey, nice tutorial, but actually I using this url https://www.googleapis.com/books/v1/volumes?q=isbn:
and using isbn numbers instead but when I run my application it says it cant decode the json text. it says
” error 1105 unable to decode json text
{
“kind”: “books#volumes”,
“totalItems”: 1,
“items”: [
{
“kind”: “books#volume”,
“id”: “Ta-XAAAACAAJ”,
“etag”: “Z6QGrwMX7Qc”,
“selfLink”: “https://www.googleapis.com/books/v1/volumes/Ta-XAAAACAAJ”,
“volumeInfo”: {
can you please help me?
For searching using ISBN, change the “?q=” in “GetBookInfo” procedure to “?q=isbn:”. Then deploy the app on your phone and just type the isbn number in app’s “Book Name” box. e.g. 0735619670
hello Sajal Dutta,
Thanks for your advice, actually I am encountering some problem with an app which uses the isbn url which you just told me about. If possible, can we talk over email?
Regards,
Shairyl
hi , i tried this app but it dont open any book and also gives error like” Error 1105: Unable to decode json text:……” and etc, plz suggest any improvement
Thanks
hello Sajal Dutta,
Excellent tutorial on json script. Just wanted to know if we can display all available books same as first result, instead of All Titles.
Thanks
K
Look at “Query parameter reference” at the bottom of the link below. See maxResults and startIndex parameters.
https://developers.google.com/books/docs/v1/using?csw=1#PerformingSearch
first of all thanks a lot for your time and great contributions.
Please help me, I’m new at this. what I want is that my application take an image of my website and show, so as you show the cover image. I’m trying to use what you mention, but I can not make it work.
please, please help me if you can.
Can you send me your json url link so I can see what typr of json structure you are using?
Thanks for answering, the question is that I do not know how to get the JSON file from my website, I did my website at jimdo.
can you explain how to extract the json file, please. I’m reading about the topic but still do not understand well.
Thank you very much for your time and valuable assistance
You should know the location of your json file if you own the website. You can ask your web host for help. Can’t help here.
Hi! Thank you very much for this! I have made pretty cool app with this tutorial! It would be very cool if i could do website also what fetches same thing that my app but i don’t have enough skill to do that :(. I have played with curl and everything but i just can’t get it right.. But thanks anyway!! Regards!
I am trying to load a youtube playlist in Web viewer component, the playlist loads successfully but the video doesnt play.
Can a web component be used to go to url and play video?
Using VideoPlayer you can. Also see: https://groups.google.com/forum/#!topic/mitappinventortest/8ATSTdf8_n4
Excellent tutorial Sajal !!!
Great contribution by you.
hello Sajal Dutta,
That’s good tutorial !!!
I want to make a similar application with the auto-complete search box data from MYSQL database.
Can you make a tutorial like that.
the following table
(Id, name, phone, address)
when I typed in the search box, and then will be shown the names and addresses automatically.
Thank you
hi sajal dutta, how to display all the data and images
hi sajal, thank’s for this tutorial, and how to display all the data and images
It’s the same way I showed above. For images, use http://ai2.appinventor.mit.edu/reference/components/userinterface.html#Image
whether there is a sample application, with .aia format, please help me
Hello Saja,
I am trying to GET data from an account which requires of me an userEmail and password before getting access.
Is there a possibility with the WEB Component to stay logged in for full acces to my data stored in the account!!!!,
Need yo help Please.
hi,
i developed the app through mit app inventor.
i created datastream in data sparkfun.com.using phant server i have to connect my android app to hardware part.but i am not getting how to parse json file values from web server.
please suggest me.
Hello Sajal
I am working with ESP8266 (nodemcu). Using TCP server in nodemcu.
App Inventor 2 Web component returns with error 1101 unable to get response with the specified URL. But from browser of mobile works ok with the same URL.
Can you let me know what changes need to be done at SERVER, so App Inventor 2 is satisfied.
Thank you for this excellent Tutorial that do work well. Do you have a similar example for Google Maps.
I am using webviewer in app inventor. In my website when I click submit button a pdf file will be generated from mysql database. In app inventor that pdf file is not opening. How can I open the pdf file directly from webviewer?
Hello Sajal,
Thank you for this really helpful tutorial.
I’m trying to code a similar app. that could get me a list of posts from a wordpress website using the wordpress REST api.
https://public-api.wordpress.com/rest/v1.1/sites/marwailn.wordpress.com/posts
I want to show the results in the same way you did. Show the first post’s title, author and a link to the original post. then having a list of the remaining posts on the website.
Could you please help in this?
I am trying to implement a similar API interaction in a set of apps I’m developing, but I am only getting an “Error 1101: Unable to get a response with the specified URL: http://public.leagueapps.io/…” After much searching through forums, etc, it appears it may be due to issues in the certificate chain. I am able to access on my test device through the browser successfully, but not from within the app, and I’ve verified the URL is correct. Any ideas?
Hallo, i have example json like this :
{“channel”:{“id”:431047,”name”:”MONITORING”,”latitude”:”0.0″,”longitude”:”0.0″,”field1″:”Suhu”,”field2″:”pH”,”created_at”:”2018-02-20T09:20:37Z”,”updated_at”:”2018-02-23T02:32:08Z”,”last_entry_id”:173},”feeds”:[{“created_at”:”2018-02-23T02:32:08Z”,”entry_id”:173,”field1″:”25.56″,”field2″:”0.00″}]}
I want get value : “field1″:”25.56″,”field2″:”0.00”
So, I use :
startTag = “field1”: and endTag = , => for value 1
startTag = “field2”: and endTag = }]} => for value 2
But, the result like :
“Suhu” => Value 1
“pH”,”created_at”:”2018-02-20T09:20:37Z”,”updated_at”:”2018-02-23T02:32:08Z”,”last_entry_id”:173} => value 2
So, it read first declaration from field1 and field2. Can you help me to fix it ? How can startTag and endTag i use to get value 25.56 and 0.00.
Please help me T_T
Thank you
Hello Sajal Dutta,
Thanks for such a great tutorial. Really helped me get some data from a webpage.
I had wanted to create parse multiple results but that seems not to work. Is there any way to go around it.
For the first results I was able to get the results to display just as intended.
I am not getting response in web.gottext…can anyone help