theWhiteFox DESIGNING & BUILDING WEBSITE / MOBILE APPS

thewhitefox

APIs

2022 January 2nd Written by theWhiteFox

Understanding APIs

API Application Programming Interface allows interfaces to communicate with one another.

A mobile phone is a perfect real world example of an API it aloows the user to access the functionality of the device through the interface, we can access a Database (DB) with a defined set of endpoints a URL of a server or service API and server requests and responses a more secure way to access data as the endpoint can only throw out certain data.

Below is several ways I have set up and consumed data from APIs.

Search API

Basic JS search bar that searchs through a JSON list of appartments. Check out the code here Github theWhiteFox repo Built using:

1/* @ Stephen O'Connor */
2async function getData() {
3 let url = '../../apart-hotel-props.json';
4 try {
5 let res = await fetch(url);
6 return await res.json();
7 } catch (error) {
8 console.log(error);
9 }
10}
11
12async function renderData() {
13 let data = await getData();
14
15 let navigation = [];
16 console.log('Array before push: ' + navigation);
17 let containName = document.querySelector('#nav');
18
19 let cities = '';
20 cities += `<option value="">Choose</option>`;
21 data.forEach(city => {
22 cities += `<option value="${city.name}">${city.name}</option>`;
23 });
24
25 let containCities = document.querySelector('#cities');
26 containCities.innerHTML = cities;
27
28 let appts = '';
29 const selectCities = document.querySelector("#cities");
30 selectCities.addEventListener('change', (event) => {
31 const {
32 value,
33 text
34 } = event.target.options[event.target.selectedIndex]
35 appts = `<option value="">Choose</option>`;
36 // city names
37 data.forEach(city => {
38 // check city name
39 if (city.name === text) {
40 if (navigation.lastIndexOf(value) == -1) {
41 navigation.splice(0,4)
42 navigation.push(value);
43 containName.innerHTML = navigation;
44 }
45
46 for (i in city.properties) {
47 appts += `<option value="${city.properties[i].name}">${city.properties[i].name}</option>`;
48 };
49 }
50 });
51 let containAppts = document.querySelector('#appts');
52 containAppts.innerHTML = appts;
53 });
54
55 const selectAppts = document.querySelector("#appts");
56 selectAppts.addEventListener('change', (event) => {
57 const {
58 value,
59 text
60 } = event.target.options[event.target.selectedIndex]
61
62 if (navigation.lastIndexOf(value) == -1) {
63 navigation.splice(1, 1)
64 navigation.push(value);
65 containName.innerHTML = navigation;
66 }
67 });
68
69 let checkin = document.querySelector('input[name=start]');
70 let checkout = document.querySelector('input[name=end]');
71 const selectSearch = document.querySelector("#search");
72
73 selectSearch.addEventListener('click', () => {
74 if (navigation.lastIndexOf(checkin.value) == -1) {
75 navigation.splice(2, 1)
76 navigation.push(checkin.value);
77 navigation.splice(3, 2)
78 navigation.push(checkout.value);
79 containName.innerHTML = navigation;
80 }
81
82 let citieNames = '';
83 data.forEach(city => {
84 citieNames = city.name;
85 for (i in city.properties) {
86 result.innerHTML += "";
87 if (navigation[0] === citieNames && navigation[1] === city.properties[i].name) {
88 const result = document.querySelector("#result");
89 result.innerHTML =
90 '<ul id="result">' +
91 '<img src="./img/appt-rent.jpg" alt="">' +
92 '<h2>Yahoo!</h2>' +
93 '<li> City: ' + citieNames + '</li>' +
94 '<li>Appt: ' + city.properties[i].name + '</li>' +
95 '<li>Open Date: ' + city.properties[i]['opening-date'] + '</li></ul>';
96 }
97 };
98 });
99
100 });
101}
102
103renderData();

Axios ReactJS API with Netlify

Axios promise based HTTP client Search unsplash netlify app. Unsplash API in ReactJS Github Repo

1import axios from 'axios';
2
3export default axios.create({
4 baseURL: 'https://api.unsplash.com',
5 headers: {
6 Authorization: 'Client-ID PASTE'
7 }
8});

Fetch API

Display User

1async function renderUsers() {
2 let users = await getUsers();
3 let html = '';
4 users.forEach(user => {
5 let htmlSegment = `
6 <div class="user">
7 <img src="${user.profileURL}">
8 <h2>${user.firstname} ${user.lastname}</h2>
9 <div class="email"><a href="mail:${user.email}">${user.email
10 </a></div>
11 </div>`;
12 html += htmlSegment;
13 });
14
15 let container = document.querySelector('.container');
16 container.innerHTML = html;
17}
18
19renderUsers();

Angular GiHub API

Search GiThub Users

JavaScript AJAX JSON repo

Yeah let's code!

Basic AJAX request

1/* @ Stephen O'Connor */
2(function () {
3
4 $.getJSON('data.json', function (data)
5 {
6 var output = '<ul>';
7 $.each(data, function (key, val)
8 {
9 output += '<li>' + val.name + '</li>';
10 });
11
12 output += '</ul>';
13 $('#update').append(output);
14 });
15
16}());
Reference
Axiosdigitalocean react axios
MDN Web API
Fetch API webpackJS Algorithms