- Software necessities
- What is Application Programming Interface (API)?
- Internet Story so Far
- Why are APIs Useful for Researchers?
- Europeana API
- API registration
- The first Go with API
- Understanding API Data (in JSON)
- XAMPP set up
- Mac OSX
- XAMPP and the first Attempt with PHP
- For Linux users
- The first go along with HTML
- HTML images and hyperlinks
- Using PHP with the Europeana API
- Building a Table View of Europeana Data
- Error coping with
- API template
- Generalising API Calls in PHP
- Try the template with Harvard Art Museums
- API for absolutely everyone
- Useful APIs
- Author’s Project Using APIs
Application Programming Interfaces (APIs) are regularly used as a means of accessing or dispensing Open Data. Indeed, over the previous few years, many humanities researchers have started to percentage their information on the net with APIs. As a end result, there are a massive wide variety of treasured datasets to be had. However, APIs are frequently tailored for developers, and it’s miles nonetheless no longer easy for the researchers with little technical enjoy to paintings on them.
This tutorial offers readers the opportunity to speedy research the basics of APIs with out previous information of programming, to begin gaining access to a large quantity of records (regularly freely) available on the web. In specific, we research primary HTML and PHP to construct a easy internet site to display API question effects of cultural historical past collections, using Europeana API. As the technique is typical, we additionally create a short template to check it with Harvard Art Museums API. In the educational, some different standards along with metadata and net servers are explained to understand APIs in a large context.
PHP is a programming language mainly suitable for internet improvement, even as HTML is a markup language to create webpages and packages. The exampes on this lesson makes use of a few basic programming, but additionally it is additionally feasible to apply replica and paste while operating with API at a basic stage.
The academic consists of two elements. The first component presents the fundamental principle of APIs:
- What is an API? and a short records of the web
- Why is it beneficial?
A realistic example begins in the 2nd element with:
- Registering for a Europeana API key
- Viewing Europeana API facts on an internet browser
- Installing XAMPP
- Using a neighborhood web server and growing a web page with PHP and HTML
- Developing a web web page for a Europeana API with PHP and HTML
- Creating an API template to get right of entry to a Harvard Art Museums API
- A net browser (Firefox, Internet Explorer, Chrome, Safari and so on)
- A textual content editor (Atom is suggested)
XAMPP is a unfastened PHP improvement platform. It includes two important packages for this tutorial: Apache net server and PHP. In this manner, you could create a test internet site on an internet server and simulate get right of entry to to APIs in your private computer.
Internet Story so Far
In this educational, we talk about net APIs (APIs used on the net), due to the fact they are used greater frequently in humanities research. To explain web APIs, permit’s in short pass lower back to the time while the World Wide Web (WWW) become born in 1989 (by Sir Tim Berners-Lee). The WWW became to start with designed for human-to-system (pc) communication. We human beings created websites on our computers, and different humans noticed them on their computers by using using net browsers. At that point, they were typically static web pages, due to the fact they have been files and the contents had been constant with the aid of webmasters. We had been simply satisfied to passively view somebody’s net pages with texts (interconnected with links) and snap shots with a Graphical User Interface (GUI). The interplay changed into primarily among humans and machines, or lets say that machines “coordinated” the human communications.
Then, we began to create dynamic web pages in which human users could engage with every other. Web pages have been dynamic, due to the fact the content changed into not constant, however dynamically changed by way of the movements of the customers. Social media are typical examples. We not best consume internet content material, but also generate it. To manipulate such net assets, we wished database structures at the back of web sites, so that we could save and control records nicely and efficiently. The recognition of consumer-generated content material has brought about the creation of large databases, and a massive amount of information: hundreds of thousands and billions of websites and datasets.
At this degree, we realised we need more device-to-machine conversation. As we from time to time have far greater information than people can sincerely browse and paintings on, we wished a method for machines to easily talk with every different. This technique is called an internet provider. APIs are common internet offerings. There are unique styles of APIs. Not most effective can machines request and reap statistics, but additionally procedure information they post. In this tutorial, we attention on acquiring beneficial statistics for studies purposes.
Let’s reflect onconsideration on a real state of affairs. You hold a ski website and need an update climate forecast for your ski fields every 1/2 an hour. You acquire the forecast from a meteorological website which includes climate information. Instead of checking this type of internet site for your very own and updating records manually, it’s miles less difficult to construct a website that can automatically fetch the weather statistics and display them at normal periods. In different phrases, a internet site communicates with another internet site. This system-to-device information change and automation is feasible when we use APIs. You can regard the API of the meteorological website as a form of (database) service.
There is a difference among growing a website with an API and embedding a snippet of a internet site in your internet site. APIs commonly offer standardised raw data and access methods, which means it’s miles simpler to control and customise the records. For example, APIs make it viable to transform Fahrenheit to Celsius, or show a line chart in place of a bar chart, which is not possible with embedding. In addition, APIs allow net builders to separate facts from layout, that is a top notch benefit whilst constructing bendy websites.
It is critical to realize that a internet site can provide each net pages and APIs. For example, at the same time as a human consumer visits a Wikipedia website to examine a pre-designed article, Wikipedia additionally offers APIs for different users to let them broaden an app, which uses Wikipedia’s system-readable raw information. As growing APIs is voluntary, there are many websites with out APIs. However, the number of APIs is developing drastically.
Why are APIs Useful for Researchers?
Apart from the technical blessings of APIs described above, what are the benefits for everyday studies users? For example, they’ll be involved to use:
- More data
- Related facts
- Interlinking records
- Remote facts
- Up-to-date data
- Different sorts of statistics (interdisciplinary take a look at)
- Data with better quality
- Data not obtainable (with the aid of yourself)
- Data with a low fee, or gratis
In general, researchers are keen to take benefit of the strength of the Internet, by way of sharing and reusing records. Therefore, “Open Data” and “information-pushed studies” were under the highlight of academia and industries for the remaining several years. APIs are one of the developing regions of this motion. By getting access to a wide range of large datasets, we are able to do a good deal greater than we ought to do before, which leads to giant alternate in our research exercise, and optimistically more new discoveries and innovations.
In the subsequent sections, we start our adventure with an API in a actual scenario.
The first API we are able to attempt is Europeana. It is considered one of the largest sources of statistics for cultural historical past in Europe. It collects facts from museums, documents, and libraries from all over Europe. At the time of writing it consists of over 50 million objects. There are pics, art work, books, newspapers, letters, sculptures, cash, specimens, 3-d visualisations, and extra.
The purpose of this phase is to create a internet site which requests after which presentations Europeana API information. To whole the project step by step, we learn how to sign up with the Europeana API, to get entry to API statistics with an internet browser, to install XAMPP, to make a simple internet web page, and to broaden any other internet web page to reveal the API records.
You should examine through the documentation of Europeana APIs right here, but it’s miles advocated to do it after having finished the academic.
In order to use the Europeana API you want to register for a key. This is loose and is carried out through their website:
The first Go with API
Your first API request need to be as smooth as feasible. You can achieve this together with your API key and an internet browser. So, allow’s neglect about technological elements in the intervening time, and simply replica and paste the following URL to the deal with bar of your web browser. Note that you need to update YOUR_API_KEY with the real key you get in your e mail.
What do you spot?
You should see loads of texts. If so, congratulations. This is your first records view. You are the use of the Europeana API already. If you spot an blunders message “Invalid API key”, make sure you have got copied your API key effectively into the URL
If you Firefox sixty six.zero.5 or later, you may see more organised established information. If you use Internet Explorer or different browsers, you may get a message (under). In this example, keep the report and open it in a textual content editor (such as Notepad or Atom).
Save the JSON report, if it does not paintings to your browser
Let’s have a better examine what you typed into your browser URL container the instance above. It is just a URL. Exactly the same as what you do when viewing a website. For example, to peer Europeana website, you type a URL https://www.europeana.ecu. There are a few distinction, even though. You use your API key after wskey=, which means you are granted personalized get right of entry to to this net deal with. It is followed via question=London. You are right. We are querying the Europeana database and our seek key-word is “London”. Europeana gives exclusive varieties of APIs, however we used the search API for this educational.
Untidy JSON statistics structure (uncooked statistics) in Chrome
Understanding API Data (in JSON)
If your browser does no longer aid a tidy JSON view (the latest Firefox have to have a pre-established JSON viewer), please replica and paste the whole facts to a web JSON viewer. It lets in us to view the statistics extra without difficulty by expanding (+ button) and collapsing (- button) the records hierarchy.
Online JSON viewer
Now, in case you appearance cautiously at the first traces of the records, you may notice some thing comprehensible:
You study literally: “apikey” is your API key. Your API get right of entry to is a hit. We can ignore what requestNumber is, however only the first 12 items (statistics) are again (to keep away from a flood of information) out of the totalResults of 1967431. After that, you’ve got actual records from the collection (i.e. the 12 items).
"call 1": "cost 1",
"name 2": "fee 2"
By specifying a call, we’re able to make a query to retrieve a corresponding statistics value. As you may see, JSON is a very easy facts layout, consequently, it is not best smooth for humans to recognize, but also for machines (computer systems) to procedure. This is why gadget-to-system communication is easier, so long as everyone follows this statistics layout. For this motive it’s far used in many APIs. Name-price (additionally referred to as “key-value”) pairs are often used in programming to store information, so it is right to be aware of this shape.
In the Europeana seek API, the real facts of users’ hobby are saved within objects. Here, you notice a slightly special shape. It carries numbers with rectangular brackets with numbers (, , …). Each bracket is an item/report and we’ve 12 data. The square bracket represents an ordered listing of values, referred to as an array. The first entry is zero. It is a chunk unusual at the start, but that is a rule, so take it as it’s far. The array is one of the statistics varieties of JSON (see also PHP facts kinds later). Similar to name-fee pairs, we are able to actually specify more than a few to retrieve facts inside the listing. Inside every array, we’ve call-fee pairs. Sometimes the name may additionally have a nesting structure, in order that arrays can be repeated. In the Europeana API, this part relies upon on each file. Some statistics have greater facts than others, so the statistics shape and values may not be consistent.
As there can be a long listing of names in a report, permit me explain some of the names:
It is out of doors of the scope of this tutorial to provide an explanation for the records version of Europeana (Europeana Data Model: EDM), however a short rationalization might be accessible, due to the fact all facts are based on it. It consists of different descriptions (i.e. metadata) about cultural historical past gadgets, inclusive of:
Dublin Core metadata to explain a cultural history object (stored in museums, libraries and files). It includes the description of generally physical aspects of the object which include name (Mona Lisa), author (Leonardo da Vinci), size (seventy seven cm × fifty three cm), date (1503-1517?), location (France), owner (Louvre museum), and sort (portray). In the Europeana API, it’s far regularly certain with prefix dc.
Metadata approximately virtual variations of the physical object. It might also include URLs in which person can view the item (both on the Europeana website and external website), virtual codecs (jpg), and licensing facts (Creative Commons).
To realize more about EDM, you could seek advice from their documentation.
As you have got already seen in the example above, to view information via APIs, you simplest need a web browser. In the case of Europeana, you could also use Europeana Rest API Console wherein you may set parameters (e.g. “London” as a search keyword) and test the records without any additional software installation.
Searching and viewing Europeana datasets is ideal, however it isn’t always very handy, due to the fact we will handiest view raw facts and/or the default statistics view. So, permit’s circulate far from the net browser and try to customize the data view.
For the following step we are able to be developing an internet web page. Note that it is a good concept to preserve the API information view open in an internet browser when doing this improvement work, due to the fact you frequently want to have a look at the facts in this way.
Now, we ought to set up a new improvement environment. Please go to XAMPP website, down load the software to your running machine, and installation it. The modern-day model is 7.2.nine. If you follow the commands underneath, it ought to be pretty truthful to put in, however take into account in which you put in XAMPP as you may must run it.
XAMPP and the primary Attempt with PHP
When your set up is complete, permit’s get commenced building our website that can get right of entry to Europeana data. First, open XAMPP. On Windows, visit the start menu and click on XAMPP Control Panel. In case of MAC, open XAMPP Control. The name of the XAMPP Control is “manager-osx”.
If you do not see a inexperienced highlight for “Apache Module”, please click on the buttons to start Apache. Then, we will use them on our nearby machines.
For Linux users
sudo ./manager-linux.run (or manager-linux-x64.run)
If you use Skype XAMPP won’t paintings as Skype might also use the same port (eighty and 443). In that case, near the utility, or trade ports (See answers)
Click Start button for Apache LModule, and it is commenced (User interface can also look a chunk exclusive depending to your OS)
Go to http://localhost/dashboard to your browser to look if Apache is operating
If you see the screens like above, the whole thing should be OK. Go to the set up folder, you’ll discover an “htdocs” folder (for Mac OSX, /Applications/XAMPP/xamppfiles/htdocs). I recommend developing a shortcut on the computing device. We must use this folder to place all the vital documents to create our internet site, so it’s miles first-rate if it’s miles without difficulty located. Right now there are simplest default documents in this folder that XAMPP has organized for us, so let’s create a cutting-edge PHP report. Inside the “htdocs” folder, create a brand new text report using your text editor and store it as helloworld.php.
Put all of the documents in htdocs folder (e.g. C:\xampp\htdocs)
As you can have heard, it is a developer’s tradition to display “Hello World” when mastering a new programming language for the first time. Open the helloworld.php to your text editor, and sort (or copy and paste) the following and store it.
print 'Hello World';
Open your web browser and sort http://localhost/helloworld.Hypertext Preprocessor inside the cope with bar. When running on PHP code, I advise maintaining the browser open to the net web page you’re editing, so as quickly as you keep the file, you can see the outcome.
You should see “Hello World” on a white heritage to your browser window. Congratulations. You have simply made your first PHP software. PHP code must usually begin with <?Hypertext Preprocessor and quit with ?>. Just like JSON, the ones lines claim that the file is PHP. print method show the following code ‘Hello World’ as textual content. In PHP, you can use both ” or “” (unmarried or double charges) to signify that the facts kind is a string (textual content) (There are other information kinds inclusive of integer, Boolean, or array, but permit’s consciousness on strings for now).
Your first PHP net page in a browser
The first go together with HTML
In the instance, PHP uses ‘Hello World’ as a everyday textual content. But, PHP can also work with HTML very well. HTML is a markup language which creates net pages and programs.
(To view the HTML of a internet site with your internet browser, right click on in a textual content vicinity on the house page (or visit the top menu bar of your browser), and choose “view web page source”).
So, allow’s make a bit trade to strive the usage of PHP to write down HTML. Change
Re-keep the file. Now, refresh the equal page on the browser. It is a superb idea to get used to frequently reloading/fresh a web web page when growing a website. The trade you made with HTML won’t be seen till the web page is refreshed.
“Hello World” have to now grow to be in ambitious. This is due to the fact the HTML tags <b></b> makes the texts, sandwiched by means of the enclosing tags, bold. HTML essentially adds an annotation to the content material in-between (<b> manner formidable).
Be cautious that most HTML tags want to have a gap tag (<b>) and a last tag (</b>). If you mistype or miss them, your net browser may not be capable of display the data well.
In programming in wellknown, you can need to be affected person and be unique. Computers might not apprehend your requests or intentions, if you mistype or neglect something. So, look at your code very cautiously.
HTML snap shots and hyperlinks
Before moving on to APIs, we would really like to do an exercising to create a simple internet site with some simple HTML and PHP coding. The first exciting stuff is to display an image on a PHP net page. Modify the preceding example as follows and store it. Be conscious that the first line has modified slightly, including <br> on the give up, which is a line smash.
print '<b>Hello World</b><br>';
print '<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/7/seventy nine/Ramesses_Vi_closeup.jpg/242px-Ramesses_Vi_closeup.jpg">';
When you view the above report in your web browser you ought to be capable of see “Hello World” in bold and an picture on the following line. The new third line prints the HTML code for placing an photo
It does so by using setting the entire HTML tag in single rates.
Hello World in bold and an picture from Wikipedia
In HTML, (enclosing) tag names are called elements. Within an detail, there are also attributes that are extra values that configure the factors or alter their behavior. Normally attributes seem as call-value pairs, and separated via =.For instance, <img> is an detail, and src=”” is an characteristic.
If you placed an photo inside the “htdoc” folder, you may also specify it the usage of the format IMAGE FILE (eg, “MyImage.jpg”) in preference to http://…
Now let’s make a real internet site. The actual electricity of Internet lies in links, so we upload a hyperlink to Wikipedia. Copy and paste the subsequent code and update with the complete preceding instance.
<?personal home page
print '<h1>My website approximately Ramesses VI </h1>';
print '<p>Ramesses VI photograph (public area) is beneath</p>';
print '<a href="https://en.wikipedia.org/wiki/Ramesses_VI">Go to Wikipedia page of Ramesses VI</a><br>';
print '<img src="https://add.wikimedia.org/wikipedia/commons/thumb/7/seventy nine/Ramesses_Vi_closeup.jpg/242px-Ramesses_Vi_closeup.jpg">';
Now, it honestly looks like a internet site, doesn’t it? <h1> is a heading tag in HTML (the most important size), at the same time as <p> is an HTML paragraph (i.e. everyday text). <a> is the link tag and href= specifies the URL, in this situation: a Wikipedia article. As attributes frequently contain more information about the detail which you don’t want to seem in the actual content, the texts “Go to Wikipedia page of Ramesses VI” is displayed in location of the prolonged URL (https://en.wikipedia.org/wiki/Ramesses_VI).
What you have got just created is the essence of all of the websites at the Internet, containing texts, links, and media (image). The only distinction is that maximum websites have a higher layout, more decorations, and possibly interactive functions. Well carried out. You have simply come to be a webmaster.
Complete web web page with an photograph and a link
Using PHP with the Europeana API
Finally, we would love to paintings on the API, using what we have learned approximately PHP. We will not cross into info of programming, however you have to understand one essential thing.
In programming, we use lots of variables. They are essentially references. In a manner, they’re much like the names in call-value pairs of JSON. They call a location wherein values are saved, in order that an unpredictable or changeable price can be accessed through predetermined names. When you want to use a price, you could in reality talk over with the variable that contains that value.
In PHP, variables are represented by way of the prefix $. Let’s anticipate the author often says “floccinaucinihilipilification”, one of the longest English phrases, meaning the act of some thing unimportant. For instance:
$it = 'floccinaucinihilipilification';
print '<p>I think he's doing '.$it.' again</p>';
Don’t worry approximately the element of the syntax. It is enough which will recognize the middle concept here. First, we positioned this lengthy word in a variable known as “it” ($it). Then, we will use $it to refer to the long word in the 2d line. The result is an HTML paragraph that reads “I suppose he’s doing floccinaucinihilipilification again”. It is like a mathematical method. You likely apprehend the subsequent without explanation. x and y are variables containing numbers.
Variables also are beneficial when numbers are assigned, so the calculation of formulae could emerge as less difficult. Let’s say, you specify a population of a country in 2018 in a variable, and use it for different statistical calculations for your code, but later you want to replace the data with the population in 2019. All you need to do is to alternate the variable. All calculations based on it is going to be robotically updated. So, the code could be very flexible and reusable.
Now, allow’s create a new PHP report known as europeana_api.personal home page.
Copy and paste the following code (update YOUR_API_KEY, however do now not take away ‘ earlier than and after YOUR_API_KEY. It is vital that the variable is a string (Remember PHP information kinds?)) and keep it. Navigate your browser to the URL localhost/europeana_api.personal home page.
$apikey = 'YOUR_API_KEY';$contents_europeana = fopen("http://www.europeana.ecu/api/v2/search.json?wskey=$apikey&query=London&reusability=open&media=genuine", "r");
$json_europeana = stream_get_contents($contents_europeana);
JSON data from Europeana API on your nearby web server
The statistics look familiar, don’t they? It is the identical JSON data we noticed in an internet browser in advance. But the massive distinction is we see it on our net server (localhost), no longer at the Europeana server.
Let’s recall how the code works, line via line. The first line defines the variable $apikey and shops the fee of YOUR_API_KEY. By doing so, we are able to no longer want to type YOUR_API_KEY each time we need it. Although we did not use it often this situation, it is a great practice, as you never know what is going to take place in destiny. The next line also defines every other variable $contents_europeana, which we use to shop information from the Europeana API.
fopen() means please open information from “http://www.europeana.eu/api/v2/search.json?wskey=”.$apikey.”&question=London&reusability=open&media=authentic”, and it’s miles reading content only (“r”), not writing it to the report. The URL includes $apikey, therefore, it is equivalent to “http://www.europeana.ecu/api/v2/search.json?wskey=YOUR_API_KEY&question=London&reusability=open&media=authentic”.
The next line proclaims another variable $json_europeana and assign stream_get_contents($contents_europeana) as a value. It obtains the statistics you just opened. Just as we open the statistics, we near it with fclose. Here, $contents_europeana is starting to do a great job of not repeating matters. Up up to now, the whole lot takes place behind the scenes and also you don’t see something to your browser. Only print $json_europeana; permits us to show the price of the variable $json_europeana, namely the JSON records you know.
In order to govern the JSON data, we want to use it in PHP format. Please upload 3 traces at the give up of europeana_api.php, but before last of PHP (?>), and save it.
$data_europeana = json_decode($json_europeana);
Refresh your browser. You see the identical JSON information for your browser, but if you look at the lowest, you find a horizontal line and numbers:
Retrieve a part of JSON facts (total Results)
json_decode converts the fee of $json_europeana (in the JSON format) into PHP code. HTML hr tag makes a horizontal line to distinguish JSON facts above and beneath. This isn’t always honestly important, however it is useful for readability functions. $data_europeana->totalResults; displays the totalResult facts. With ->, we are able to seek advice from a selected position of data hierarchy and gain the facts fee, in this example, totalResults. In this way, we will specify part of data we need to display.
The subsequent step is the final method to the Europeana search API on this tutorial. We will create a desk view of the identical information we were using so you have revel in customizing the manner the facts is displayed.
Building a Table View of Europeana Data
So a ways, the data we have accessed are not smooth to read. So, we are able to re-organise them to construct a table view. We will upload code to the work you have already done. Delete print $json_europeana; and print $data_europeana->totalResults; and add the subsequent lines of code on the give up of europeana_api.personal home page, but, again, earlier than closing of PHP (?>). Have a have a look at the file within the browser. You ought to see a desk with a header row. We simply want to place facts in the desk later.
// Table view of Europeana statistics
print '<desk border=1><tr><th>Title</th><th>Data Provider</th><th>External Link</th><th>Thumbnail</th></tr>';print '</table>';
Table header is created
In the above code, the hr tag is to visually separate the preceding outputs from the desk we’re running on now.
On the second one line, // indicates a “remark”. It tells the computer to disregard this line, so “Table view of Europeana information” is skipped. Developers use feedback to document their code, that will understand what the code is for and what it does within the destiny, as can other developers who want to paintings on the identical code. People frequently forget what they have executed, so it is the first-class exercise to document the records of the code.
On the 0.33 line, we set up a desk with HTML code. Full explanation can be discovered in a HTML educational, however the first line <table border=1> defines a table with a unmarried width border line. Note that print “</table>”; at the quit of the example is a closing HTML tag. While <tr></tr> (desk row) generates a header row in a desk, <th></th> (table header) gives columns and heading names within.
Next, we can control Europeana records which now have to be saved in the variable $data_europeana. In the distance between the desk and /table tags, upload the subsequent code:
foreach($data_europeana->gadgets as $item) print '<td><a href="'.$item->guid.'">' .$object->identify[zero].'</a></td>';print '<td>'.$item->dataProvider[zero].'</td>';print '<td><a href="'.$item->edmIsShownAt.'">View on the company internet site</a></td>';print '<td><a href="'.$object->guid.'"><img src="'.$item->edmPreview.'"></a></td></tr>';
Re-store your file and refresh your browser. What you see now’s what textual content facts of JSON really contains. As it has URLs that factor to images, we are able to display the snap shots within the desk.
The table now consists of the identify, information issuer, external link, and thumbnail. Don’t worry in case you see errors in front of the table (we are able to repair them later). Just discover the net page you created to get a sense of what you could do.
Table shows Europeana information
Let’s try and apprehend the good judgment at the back of what we have created. As mentioned earlier, Europeana facts are stored in an array known as objects. Within it, every piece of information is saved so as and may be accessed by means of the range corresponding to its location in the array, from  to . In order to manipulate facts inside an array, we want to use foreach(). It’s a “Foreach loop” – a function that repeats a project for objects in a chain. In our case, inside the round brackets, we assign a new variable known as $object for each file of the array ($data_europeana->gadgets as $object). In different words, we are able to get right of entry to each document from [zero] to  with the variable $object. The loop can be specified inside curly brackets . It is less complicated to understand whilst searching at the following lines, so go away it for now. We ought to print the datasets, so print is used usually in the desk. <td></td> represents a row in the desk.
Now, we would really like to scrutinise Europeana’s JSON information, due to the fact we should specify what information have to be displayed, as we don’t want they all. Open a new window/tab and go to http://www.europeana.ecu/api/v2/seek.json?wskey=YOUR_API_KEY&question=London&reusability=open&media=true, remembering to switch YOUR_API_KEY with the best string. You should use the JSON viewer to perceive the statistics you would love to fetch.
Let’s take a glance line by line in the foreach loop. Each print line corresponds to a column within the desk. The first line makes the first column: “Title”. The row has <a></a>, implying it is a link. href specifies the target URL to which the person jumps after they click at the link, and between <a></a> might be the text that becomes clicakable. You can ignore the detail of the syntax for now, but in our case, $object->guid is the URL and $object->identify is the textual content.
While guid is the URL of the object web page in Europeana, identify is the identify of the object. We use  after name, due to the fact it’s miles saved in the first call/key in an array (from time to time there’s simplest one name/key in an array). As a end result, the link and texts works as we supposed in the first column.
For the second one column, there is not anything greater than <td></td>, implying only a textual statistics could be inserted. The content material is dataProvider, that’s understandable, as we have already created the header “Data Provider” within the preceding section. The 1/3 column has again hyperlink factors. edmIsShownAt is targeted for the hyperlink, and simple sentence: “View at the company website” is used for display. The remaining column additionally has a hyperlink for guid, however additionally, an photograph is created in-among. When an photograph is sandwiched by means of a link, the previous is connected and clickable. Thus, the photograph certain at edmPreview[zero], will have a link to the internet web page precise at guid, whilst it is clicked. You can double-test if it’s miles operating, or not in your browser.
To sum up, foreach loops a project over an array. The repeating detail is described in () and the project is defined in . In our case, we show the records values of every object (from [zero] to [eleven]) repeatedly, without writing  to [eleven] separately. Code typically consists of a lof of functions like foreach to execute different forms of duties. That’s why customers can do many things with software.
Finally, permit’s try to make it tidy. It isn’t always 100% quality, due to the fact we may additionally have error messages. They basically tell you that PHP can not process Europeana records, because the records values we asked don’t exist in the Europeana data.
So, if you click the photo of a document, you are directed to the suitable internet site, however if you do the identical for another, you may not attain the internet site, surely because there’s no hyperlink. Actually our net web page nonetheless works, however, because of the absence of records, the mistake messages may be displayed.
As written earlier on this educational, records systems and values might not constantly be constant, consequently, we have to do some thing when information values are not to be had. This is called “exception coping with”, and it means specifying what must happen if an operation fails.
In order to restore the bugs, we have to put into effect the subsequent: “show facts handiest while they’re available and forget about if they’re now not”. To this stop, we will replace our most current code additions with the following:
foreach($data_europeana->objects as $item) print '<td><a href="'.(isset($object->guid)?$item->guid:'').'">' .(isset($object->title[zero])?$item->name:'').'</a></td>';print '<td>'.(isset($object->dataProvider)?$object->dataProvider[zero]:'').'</td>';print '<td><a href="'.(isset($object->edmIsShownAt[zero])?$item->edmIsShownAt[zero]:'').'">View on the company internet site</a></td>';print '<td><a href="'.(isset($item->guid)?$item->guid:'').'"><img src="'.(isset($object->edmPreview[zero])?$item->edmPreview:'').'"></a></td></tr>';
The above is nearly equal to the preceding example, but isset is added. It is a PHP function that exams if records is set (exists) or now not inside brackets (). In addition, the following makes a conditional project:
isset($statistics)?’$statistics is set’:‘$data isn't always set’;
In this example, if $statistics is available, the textual content “$records is ready” can be used, and if $facts isn’t to be had, the textual content “$data is not set” will be used. We can execute a venture based on this code for a condition. For instance, inside the first column of our table, if $object->guid is about, we use it. Otherwise empty textual content (“”) is used. So, the hyperlinks will work properly. We use this sample of code each time facts is called from the API (every time $object-> appears). As a end result, with any luck blunders messages have to disappear.
Unfortunately, there’s no right manner to know in advance, if the statistics we want are available or now not, due to the fact all we can do is ask Europeana for it and wait to find out if it’s far there. This configuration is an advantage that, if there may be a little mistake inside the request, something works at least, without breaking the whole lot else, but a disadvantage in that we want control exceptions and errors.
Note that we don’t take care of all errors scenarios in this academic. For example, we didn’t keep in mind the capability scenario whereby the facts ($object->edmIsShownAt) isn’t an URL. This is due to the fact this academic is NOT a programming lesson, but an introduction. To increase a right utility, you want to delve into greater PHP programming.
Big congratulations! You have just made a easy but satisfactory web web page inside a short space of time that systems API statistics from Europeana in a customized way.
Generalising API Calls in PHP
The final phase attempts to create an API template, primarily based on the code we created. The following code is a middle a part of what we just produced. You handiest should exchange some parameters in the template. As typical, YOUR_API_KEY need to be changed. It is usually recommended that you update the name of VARIABLE1, VARIABLE2, and VARIABLE3 with more significant names. HTTP (information kind is string) is the URL of an API. Most APIs require you to insert $apikey within HTTP, as you have got seen earlier than. But, different parts should remain the same.
$apikey = 'YOUR_API_KEY';$VARIABLE1 = fopen('HTTP', 'r');
$VARIABLE2 = stream_get_contents($VARIABLE1);
$VARIABLE3 = json_decode($VARIABLE2);
In addition, you’ll want to alter what you would like to do with the actual information. For instance, the following code generalises the statistics retrieval part, best along with foreach to cope with arrays and print the information values in a loop.
foreach($records as $item) print 'WHATEVER YOU WANT TO DISPLAY';
By combining those above snippets of code, you’ll be able to manage numerous sorts of JSON data.
Try the template with Harvard Art Museums
Let’s take a look at if the API template certainly works with different APIs. For this, we are able to use the Harvard Art Museums API. Please have a brief have a look at their API documentation. As usual, you need to get an API key first.
Once you get it, let’s quick take a look at their item seek API on a web browser to understand the records structure: https://api.harvardartmuseums.org/object?apikey=YOUR_API_KEY&keyword=andromeda
Records are present in the form of an array within a information element. This gives you an idea what facts you would really like to fetch. Guess what going for walks the following code really indicates on your browser:
<?personal home page
$apikey = 'YOUR_API_KEY';$contents_harvard = fopen("https://api.harvardartmuseums.org/object?apikey=$apikey&keyword=andromeda", 'r');
$json_harvard = stream_get_contents($contents_harvard);
print($json_harvard);// For display purposes, <hr> are delivered numerous instances on this file
$data_harvard = json_decode($json_harvard);
print '<hr>';//the following block of code will move right here?>
Apparently, new names have been assigned as VARIABLEs. For example, $contents_harvard and $json_harvard are used. But, all others need to look the identical.
If you are geared up, you may upload the subsequent code underneath the remark in the preceding instance:
foreach($data_harvard->facts as $item) print '<td>'.(isset($item->title)?$object->title:'').'</td>';print '<td>'.(isset($item->dated)?$object->dated:'').'</td>';print '<td>'.(isset($item->creditline)?$item->creditline:'').'</td>';print '<td><a href="'.(isset($object->url)?$object->url:'').'">View at the website</a></td>';print '<td><a href="'.(isset($item->isShownAt)?$object->primaryimageurl:'').'"><img src="'.(isset($item->primaryimageurl)?$object->primaryimageurl:'').'" top="a hundred" width="a hundred"></a></td></tr>';print '<br>';
Outcome of harvard_api.personal home page
Hopefully, you spot something very much like europeana_api.php. This time, we without a doubt gift each file separated by <br> (line spoil), and do no longer create a table on cause. For this reason, our effects look untidy, however that genuinely implies you can do whatever you want. One addition is the <img element specifies the scale of the photo as peak=”one hundred” width=”a hundred”, thus all photos have the same size.
The factor is the API template can be reused and custom designed, therefore, the most difficult component would be the exam of the underlying records model of a given API, and the dealing with of statistics structures. To manage that, you want to study an API’s documentation cautiously. It should additionally be mentioned that this template isn’t always a magic template. It simply provides a shortcut for beginners which can be carried out for standard question APIs. As there are different styles of APIs, you can want some other technique and also you have to always seek advice from an API’s documentation while in doubt.
API for anybody
If you may learn a bit of programming, you are not constrained through what a internet site gives by way of default. You at the moment are free to build your personal device or device, as an instance, to select, clear out, compare, technique, analyse, visualise, and proportion information in new ways. So, what are you looking ahead to? Be brave and start your new challenge.
- The New York Times
- The Digital Public Library of America
- Archives Portal Europe
- The Open Library
- List of useful APIs for museums
Author’s Project Using APIs
- James Cook Dynamic Journal (JCDJ)…Contextualisation of a e book from The Open Library
- WiQiZi…Gamification of Wikipedia/DBpedia
- CAROL…Exploring the books from the Open Library in context