Skip to content

Instantly share code, notes, and snippets.

@patbi
Last active July 26, 2019 08:11
Show Gist options
  • Save patbi/a2418f70a5c5d03aa0d9aa400cd34a64 to your computer and use it in GitHub Desktop.
Save patbi/a2418f70a5c5d03aa0d9aa400cd34a64 to your computer and use it in GitHub Desktop.
API FETCH

API FETCH Basic principles of

Mentor Patrick BIYAGA Course

Basic principles of API Fetch.

Website For Learn - https://developer.mozilla.org/en/docs/Web/API/Fetch_API/Using_Fetch

Methods that can be used Fetch : https://developer.mozilla.org/en/docs/Web/API/WindowOrWorkerGlobalScope/fetch

fetch can take several methods first of all : the entry then init

Promise<Response> fetch(entrée[, init]);
  or
fetchResponsePromise = fetch(resource, init);

website giving false API call and sending you back from JSON

website : https://jsonplaceholder.typicode.com/

so we'll take the call to /users as an example, which returns a list of users

to make a a stroke of fetch by passing him a first parameter that will send me back a promise

EXAMPLE :

fetch('https://jsonplaceholder.typicode.com/users')
	.then(response => response.json()).then(console.log)

and we can also simplify our lives by using the keywords await and async

EXAMPLE :

	const getUsers = async function () {
		let response = await fetch('https://jsonplaceholder.typicode.com/users')
		let data = await response.json()
		console.log(data)
	}
	
	getUsers()  // returns list of users

how to check that you have a valid answer?

EXAMPLE :

const getUsers = async function () {
	let response = await fetch('https://jsonplaceholder.typicode.com/usersdhsgdsdjsjdsjdkdjskdj')
	if (response.ok) {
		let data = await response.json()
		console.log(data)
	}else {
	console.error('server return : ', response.status)
 }
}

getUsers()

to better capture the error we can use a try - catch like this :

const getUsers = async function () {
	try {
		let response = await fetch('https://127.0.0.1:4848')
		if (response.ok) {
			let data = await response.json()
			console.log(data)
		} else {
		console.error('server return : ', response.status)
		}
} catch (e) {
 	console.log(e)
 	}
}

getUsers()

post information :

EXAMPLE :

const insertPost = async function (data) {
	let response = await fetch('https://jsonplaceholder.typicode.com/posts', {
	method: 'POST',
	headers: {
		'Content-Type': 'application/json'
},
	body:JSON.stringify(data)
	})

	let responseData = await response.json()
	console.log(responseData)
}


insertPost({
	name: 'Marie Claire',
	age: 29
})

the following very soon good weekend @Patrick BIYAGA

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment