James Williams
Birmingham Newman University
jwilliams@staff.newman.ac.uk
3-hour session
// Example: Fetching data from a REST API
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
// HTTP Methods
GET /api/users // Retrieve data
POST /api/users // Create new data
PUT /api/users/123 // Update data
DELETE /api/users/123 // Delete data
// Status Codes
200 - OK
201 - Created
400 - Bad Request
401 - Unauthorized
404 - Not Found
500 - Internal Server Error
// Basic GET request
fetch('https://api.example.com/users')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not
ok');
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error(error));
// POST request with data
fetch('https://api.example.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
name: 'John Doe',
email: 'john@example.com'
})
});
// API Key authentication
fetch('https://api.example.com/data', {
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'X-API-Key': 'your-api-key'
}
});
// OAuth 2.0 flow
const clientId = 'your-client-id';
const redirectUri = 'https://yourapp.com/callback';
const authUrl =
`https://api.example.com/oauth/authorize?client_id=${clientId}&redirect_uri=${redirectUri}&response_type=code`;
// Geolocation API
navigator.geolocation.getCurrentPosition(
position => {
console.log('Latitude:', position.coords.latitude);
console.log('Longitude:',
position.coords.longitude);
},
error => console.error('Error:', error)
);
// Local Storage API
localStorage.setItem('user', JSON.stringify(userData));
const user = JSON.parse(localStorage.getItem('user'));
// Web Audio API
const audioContext = new AudioContext();
const oscillator = audioContext.createOscillator();
// Including libraries
<script
src="../../libs/jquery/jquery.min.js"></script>
<script
src="../../libs/lodash/lodash.min.js"></script>
// Using jQuery
$('#element').hide().fadeIn(1000);
// Using Lodash
const uniqueItems = _.uniq(array);
// DOM manipulation
$('#myElement').addClass('highlight');
$('.items').each(function(index, element) {
$(element).text('Item ' + (index + 1));
});
// Event handling
$('#button').on('click', function() {
console.log('Button clicked!');
});
// AJAX requests
$.ajax({
url: 'https://api.example.com/data',
method: 'GET',
success: function(data) {
console.log(data);
},
error: function(xhr, status, error) {
console.error(error);
}
});
// Basic GET request
axios.get('https://api.example.com/users')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
// POST request
axios.post('https://api.example.com/users', {
name: 'John Doe',
email: 'john@example.com'
})
.then(response => console.log(response.data));
// Request configuration
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = 'Bearer token';
// HTML
<canvas id="myChart"></canvas>
// JavaScript
const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Red', 'Blue', 'Yellow', 'Green'],
datasets: [{
label: 'Dataset 1',
data: [12, 19, 3, 5],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)'
]
}]
},
options: {
responsive: true,
scales: {
y: {
beginAtZero: true
}
}
}
});
Interactive: Hover over data points for details
Responsive: Charts automatically resize
Animated: Smooth transitions and animations
Customizable: Colors, fonts, and styling options
Click the buttons to see different chart types powered by Chart.js!
Interactive: Zoom, pan, and click on the map
Markers: Click "Add Marker" to place markers
Shapes: Add circles and polygons to the map
Responsive: Works on desktop and mobile devices
This map is powered by Leaflet.js - a popular open-source mapping library!
// OpenWeatherMap API
const apiKey = 'your-api-key';
const city = 'London';
fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`)
.then(response => response.json())
.then(data => {
const temperature = data.main.temp;
const description = data.weather[0].description;
const humidity = data.main.humidity;
document.getElementById('weather').innerHTML = `
Temperature: ${temperature}°C
Description: ${description}
Humidity: ${humidity}%
`;
})
.catch(error => console.error('Error:', error));
// Twitter API (example)
const twitterApi = {
consumerKey: 'your-consumer-key',
consumerSecret: 'your-consumer-secret',
accessToken: 'your-access-token',
accessTokenSecret: 'your-access-token-secret'
};
// Facebook Graph API
fetch('https://graph.facebook.com/me?access_token=your-token')
.then(response => response.json())
.then(data => console.log(data));
// Instagram Basic Display API
const instagramUrl =
'https://graph.instagram.com/me/media?fields=id,caption,media_type,media_url&access_token=your-token';
// Stripe payment integration
const stripe = Stripe('your-publishable-key');
const elements = stripe.elements();
// Create card element
const card = elements.create('card');
card.mount('#card-element');
// Handle payment
const form = document.getElementById('payment-form');
form.addEventListener('submit', async (event) => {
event.preventDefault();
const {error, paymentMethod} = await
stripe.createPaymentMethod({
type: 'card',
card: card,
});
if (error) {
console.error(error);
} else {
console.log('Payment method:', paymentMethod);
}
});
// Comprehensive error handling
async function fetchData(url) {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status:
${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
if (error.name === 'TypeError') {
console.error('Network error:',
error.message);
} else {
console.error('API error:',
error.message);
}
// Show user-friendly error message
showErrorMessage('Failed to load data. Please try
again.');
throw error;
}
}
// Secure API key handling
// ❌ Bad: Exposing API key in frontend
const apiKey = 'sk-1234567890abcdef';
// ✅ Good: Use environment variables
const apiKey = process.env.API_KEY;
// ✅ Good: Use backend proxy
fetch('/api/weather?city=London') // Backend handles API key
// Input validation
function validateInput(input) {
if (typeof input !== 'string' || input.length > 100) {
throw new Error('Invalid input');
}
return input.trim();
}
// Caching with localStorage
function getCachedData(key, ttl = 300000) { // 5 minutes
const cached = localStorage.getItem(key);
if (cached) {
const { data, timestamp } = JSON.parse(cached);
if (Date.now() - timestamp < ttl) {
return data;
}
}
return null;
}
// Request batching
const batchRequests = (requests) => {
return Promise.all(requests.map(req => fetch(req)));
};
weather-dashboard.htmlTime: 45 minutes
This task will help you understand API integration and external library usage
Take a break, ask questions, or catch up on the previous task.
Next: Secondary slides and Task 2
// Retry mechanism
async function fetchWithRetry(url, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
const response = await fetch(url);
if (response.ok) return
response.json();
} catch (error) {
if (i === maxRetries - 1) throw
error;
await new Promise(resolve =>
setTimeout(resolve, 1000 * (i + 1)));
}
}
}
// API mocking
const mockApi = {
get: (url) => Promise.resolve({ data: mockData[url] }),
post: (url, data) => Promise.resolve({ data: { id: Date.now(),
...data } })
};
// WebSocket connection
const socket = new WebSocket('wss://echo.websocket.org');
socket.onopen = function(event) {
console.log('Connection established');
socket.send('Hello Server!');
};
socket.onmessage = function(event) {
console.log('Message from server:', event.data);
};
socket.onclose = function(event) {
console.log('Connection closed:', event.code, event.reason);
};
socket.onerror = function(error) {
console.error('WebSocket error:', error);
};
// GraphQL query
const query = `
query GetUser($id: ID!) {
user(id: $id) {
id
name
email
posts {
title
content
}
}
}
`;
// Fetch GraphQL data
fetch('/graphql', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
query: query,
variables: { id: '123' }
})
});
// Jest test example
describe('Weather API', () => {
test('fetches weather data successfully', async () => {
const mockResponse = {
main: { temp: 20, humidity: 65 },
weather: [{ description: 'sunny' }]
};
global.fetch = jest.fn(() =>
Promise.resolve({
json: () =>
Promise.resolve(mockResponse)
})
);
const weather = await fetchWeather('London');
expect(weather.temperature).toBe(20);
});
});
social-media-app.htmlTime: 45 minutes
This task will help you understand complex API integrations and multi-platform development
Project Planning and Development - Building complete web applications