Coding Notes

APIs

By Rae

APIs

Access Real Data

Build more interesting apps

Prepare to learn full-stack

Notes

  • Getting data from a server
    • The server hosts an API - exposed endpoints we can access for getting data from the server.
    • The server doesn't give us access to evertying, just the things they want us to have.
  • Pre-written code
  • Local Storage is a version of an API.
  • Server Status Codes
    • 200 - everything went ok
    • 403 - client tried to access forbidden information
    • 500 - internal server error
    • anything in the 500 range means the server had an error.
  • The Network Tab
    • In the inspector, fourth in the row.
    • Used for debugging and testing
    • XHR filter will not show every request, but only Ajax requests that usually receive JSON as a response.
    • The requests are shown under Name
    • If you select a request it will show more information about the request to the right in the headers tab.
    • The preview tab will show the sent out JSON data.
  • HTTP Requests
    • Components of a Request
      • Path (URL)
      • Method (GET, POST, PUT, DELETE, etc.)
      • Body
      • Headers - extra information that isn't included in the above.
    • fetch("URL") .then(response => response.json()) .then(data => console.log(data)) , a get request.
    • The scheme or protocal of a URL is https://
    • Other protocols are ftp:// or SMTP
  • JSON
    • Similar to JS
    • JSON objects have strings for keys { 'key': 'string value', 'boolean': true, 'number': 10, }
    • In Dev Tools: network tab, XHR
    • The language of data on the web.
  • To fetch with JSON fetch('API URL') .then(response => response.json()) .then(data => console.log(data))
  • Async JS will let all other JS run first
  • Compontents of a request.
    • URLs
    • REST
  • HTTP
    • Hypertext Transfer Protocol
    • Components: Path (URL), Method (get, post, put, delete, patch, options), body,
    • Path (URL)
      • Adress where your desired resource lives
      • Two main portions are BaseURL vs. Endpoint
      • A base URL is the part of the URL that won't change, no matter which resource we want to get from the API
      • An endpoint specifies exactly which resource we want to get form the API.
      • https://google.com/blog/post, https://google.com/blog is the BaseURL and /post is the Endpoint
      • JSON in browser.
  • Request Methods
    • GET - Getting data
    • POST - Adding new data (like a block post or facebook post)
    • PUT - Updating existing data
    • DELETE - Removing data
    • PATCH
    • OPTIONS
    • To request a specific request method in fetch add a second parameter. fetch("API URL", {method: "request type"}) GET is the default.
  • The Request Body
    • The data we want to send to the server.
    • Methods a body uses: POST and PUT requests.
    • Needs to be turned into JSON first.
    • fetch('API URL', { method: "POST or PUT", body: JSON.stringify({ string: "", boolean: true }) })
    • Extra/meta information about the outgoing request.
    • Auth, body info, client info, etc.
    • To change the header to sending JSON and not plain text fetch('API URL', { method: 'POST or PUT', body: JSON.stringify({ string: "", boolean: false }), headers: { 'Content-Type': 'application/json' } })
  • Fetch: const options = { method: 'method type', body: JSON.stringify(data), headers: { 'Content-Type': 'application/json' } } fetch('API URL', options) .then(response => response.json()) .then(data => console.log(data)) will log the data.
  • REST
    • REpresentational, State, Transfer
    • A design pattern to provide a standard way for clients and servers to communicate.
    • Principles of REST
      • Client and Server separation
      • Statelessness - server requests are not maintained
      • Accessing "Resources"
      • Nested Resources
  • Query Strings
    • Documentation sometimes refers to these as parameters.
    • A way to filter the results.
    • Adding ? in a URL allows you to add a query string. /whatever?type=thing.
    • Adding & at the end of a query string will allow you to add another query string. /whatever?type=thing&brand=thing.
    • Booleans will be parsed as a string in the API.
  • Async and Await
    • async function functionName() { const response = await fetch("API URL") const data = await response.json() code for actions }
  • Geolocation
    • To get the users longitude and latitude: navigator.geolocation.getCurrentPosition((position) => { console.log(position.coords.latitude) console.log(position.coords.longitude) })
    • The position coords returns accuracy, altitude, altituceAccuracy, heading, latitude, longitude, speed, and __proto__. The timestamp returns a timestamp.
    • To insert the weather icon: navigator.geolocation.getCurrentPosition(position => { fetch(`https://URL/openweathermap/data/2.5/weather?lat=${position.coords.latitude}&lon=${position.coords.longitude}&units=imperial`) .then(res => { if (!res.ok) { throw Error("Weather data not available") } return res.json() }) .then(data => { console.log(data) const iconUrl = `https://openweathermap.org/img/wn/${data.weather[0].icon}@2x.png` document.getElementById('weather').innerHTML = `weather icon` }) .catch(err => console.error(err)) });