Name of code : API Unsplash

Categorie : API

Ce code utilise l'API Unsplash pour récupérer une image aléatoire avec une clé d'accès API. Il utilise également XMLHttpRequest pour envoyer une requête GET à l'API, puis traite la réponse JSON pour extraire l'URL de l'image, l'attribut alt de l'image, le titre de la page et le nom de l'auteur de la photo. Enfin, il utilise JavaScript pour mettre à jour les éléments HTML correspondants avec ces informations.

Demo : API Unsplash

HTML

CSS

Javascript

Visual Sstudio Code

<!DOCTYPE html>
<html>
<head>
	<title>Ma page magnifique</title>
	<style>
		body {
			background-color: #F5D0A9;
			font-family: Arial, sans-serif;
			font-size: 20px;
			text-align: center;
			margin: 0;
			padding: 0;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			height: 100vh;
		}
		.container {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			max-width: 600px;
			padding: 20px;
			background-color: white;
			box-shadow: 0px 0px 10px rgba(0,0,0,0.3);
			border-radius: 10px;
		}
		img {
			max-width: 100%;
			height: auto;
			margin-bottom: 20px;
			border-radius: 5px;
			box-shadow: 0px 0px 5px rgba(0,0,0,0.3);
		}
		h1 {
			font-size: 50px;
			margin-bottom: 20px;
		}
		p {
			margin-bottom: 20px;
		}
	</style>
</head>
<body>
	<div class="container">
		<img id="myImage" src="" alt="Une image magnifique">
		<h1 id="myTitle">Ma page magnifique</h1>
		<p id="myText">Chargement en cours...</p>
	</div>

	<script>
		const xhr = new XMLHttpRequest();
		xhr.responseType = 'json';
		xhr.open('GET', 'https://api.unsplash.com/photos/random?client_id=YOUR_CLIENT_ID', true); // Remplacez YOUR_CLIENT_ID par votre propre clé d'accès API Unsplash
		xhr.send();
		xhr.onreadystatechange = function() {
			if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
				const response = xhr.response;
				const imageUrl = response.urls.regular;
				const imageAlt = response.alt_description;
				const imageTitle = response.description;
				const authorName = response.user.name;

				const myImage = document.getElementById('myImage');
				myImage.src = imageUrl;
				myImage.alt = imageAlt;

				const myTitle = document.getElementById('myTitle');
				myTitle.textContent = imageTitle;

				const myText = document.getElementById('myText');
				myText.textContent = 'Crédit photo : ' + authorName;
			}
		}
	</script>
</body>
</html>