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)) });

Resources

JSON Lint
Formats and validates your JSON code.
JSON Formatter
A chrome extention that formats JSON.
Using Fetch
The MDN Documentation on how to use fetch.
Zapier's Introduction to APIs
An introduction to APIs course.
REST API Tutorial
An in-depth REST API Tutorial
Using a weather API
OpenWeather map will get the users weather by location.
MDN Docs about using the geolocation api
MDN Docs about the getCurrentPosition() method.
Be sure your computer is allowing location access to your browser.

Definitions

API
Application Programming Interface
An API is any tool that helps connect your program with someone else's program.
Clients
Any device that connects to the internet to get data from somewhere else (makes a request).
Laptop, phone tablet, any smart device (watch, doorbell, robot vacuum, even a server)
Server
A computer that accepts requests form clients asking for something, then responds to the client with that thing (HTML page, image or file, plain data).
Most likely running lynux.
Request
When a device asks for a resource (data, img, HTML page, authentication token, etc.).
Requires a connection to the internet somehow.
Response
The replay to the request.
Could contain the resource (HTML, JSON, data, etc.) asked for by the client.
Could contain a response saying the client isn't authorized to receive the resource.
JSON
Javascript Object Notation
The language of data on the web (mostly)
Resource
HTML page, JSON, an image file, etc.
HTTP
Hypertext Transfer Protocol
HTTP is a protocol for determining how Hypertext (text) should be transferred over the internet.
HTTPS is just the more secure version of HTTP.
URL Parameter
A variable inside the URL that acts as a placeholder for the real value (oftentimes they replace the ID of the resource).
URL/whatever/:id, :id is a URL parameter.

Questions

  • Why is it HTTP not HTP?

Opinions