1 of 46

#INCLUDE

Create For Community

Tech Cohort Workshop 5

INCLUDE

2 of 46

Agenda

Backend!

  • APIs
  • Asynchronous Functions
  • Error Handling Practices
  • Backend Toolset

INCLUDE

3 of 46

INCLUDE

What is Backend?

4 of 46

Basically, handles all the logic of the app.

  1. Server takes in requests from some endpoint/device
  2. Processes the request and formats/handles the request for the user
  3. Sends back an indication (typically JSON data) that the task was complete as the response

Key ideas: Servers, Databases, APIs, etc.

Core Idea

INCLUDE

5 of 46

  1. Abstraction: Hide all the nitty gritty details from the user
  2. Computation: More expensive to handle all the data processing in the front-end
  3. Easier to debug: Can distinguish between issues for frontend and backend

What’s the point?

INCLUDE

6 of 46

INCLUDE

APIs

7 of 46

Application Programming Interface

  • Way for two interfaces (i.e your computer and a server) to interact and transfer data if desired
  • Mediator between client/server
  • Each API has their own server endpoint URL
    • EX: Paypal, Google Maps, etc

INCLUDE

8 of 46

INCLUDE

9 of 46

API Endpoints

  • Found within the URL of your browser
  • Typically indicated by /api that comes before it

Eg, http://localhost:3000/api/contact-form,

https://pokeapi.co/api/v2/pokemon?offset=20&limit=30

INCLUDE

10 of 46

URL Query Parameters

  • Additional Parameters provided by the user
    • key=value pairs
  • First Query Parameter has ? before it
    • Following query params will be split by &
  • Useful for specifying filtering conditions used in a request

INCLUDE

11 of 46

INCLUDE

Live Demo

12 of 46

INCLUDE

REST APIs

13 of 46

Representational State Transfer API

API that follows RESTful conventions: CRUD

Used across the web for data handling across many devices

INCLUDE

14 of 46

Create, Read, Update, Delete

  • Create: Making new data in a server

POST (url) + payload/body (new data)

  • Read: Accessing existing data in a server

GET (url)

  • Update: Changing existing data in a server

PUT (url) + payload/body (existing data identifier, new

data)

  • Delete: Removing existing data in a server

DELETE (url) + payload/body (existing data identifier)

INCLUDE

Core Idea: Create, Read, Update, Delete

Each operation consists of a conventional HTTP request method

15 of 46

INCLUDE

16 of 46

INCLUDE

RESTful Naming Conventions

17 of 46

Nouns not Verbs

INCLUDE

18 of 46

Pluralize, unless Singleton resources

INCLUDE

19 of 46

Use Hyphens to improve readability

INCLUDE

20 of 46

Use queries to filter/sort/paginate

INCLUDE

21 of 46

INCLUDE

Live Demo

22 of 46

INCLUDE

Fetch

23 of 46

JavaScript Fetch

INCLUDE

  • fetch: Built in async JS function used to make a request to some API
  • Takes in a API url, headers, methods, body, etc
    • Loads of options for a fetch call (refer to docs)

24 of 46

INCLUDE

Request & Response

25 of 46

Request & Response Objects

  • Request Object: User’s desired action for some API
    • Contains CRUD action, and possibly additional data
  • Response Object: Data sent by the API to indicate the overall handling of the user’s request
    • May include data stored in server depending on request type

INCLUDE

26 of 46

Various Response Codes

Key Response Codes

200: Success

404: Not Found

500: Internal Server Error

Many more exist, but these are the most frequent

INCLUDE

27 of 46

INCLUDE

Synchronous vs. Asynchronous

28 of 46

Synchronous vs. Asynchronous

INCLUDE

Synchronous Programming

  • Execute one thing at a time
  • Wait for one task to finish before moving on to the next one
  • When processes are dependent on one another

Asynchronous Programming

  • Execute multiple things at a time
  • Parallelization
  • Achieve outcomes faster
  • When processes are independent of one another

29 of 46

INCLUDE

Promises

30 of 46

JavaScript Promises

  • JavaScript’s way of indicating that a request to some external API is being processed, and will eventually return that response even if it is not immediate.
    • Considered a class, so use new Promise(async task) to create a promise
    • There can be multiple promises going at once

Think about how you might promise to pay your friend back after a meal.

Issues: Very verbose & can lead to long chains…

INCLUDE

31 of 46

Resolve & Reject

Functions that are built in parameters to a Promise Object

  • Resolve: Promise request was successfully handled → What to do now?
  • Reject: Promise request FAILED at some point → How do I handle the error?

INCLUDE

32 of 46

Then & Catch Methods

  • .then(): Called after a Promise is resolved
    • Used to pass in resolve function to handle the resulting response
  • .catch(): Called after a Promise is rejected
    • Used to pass in reject function to handle resulting error

INCLUDE

33 of 46

INCLUDE

Async & Await

34 of 46

JavaScript Async & Await

Alternative to JS Promises that offers cleaner & more readable code for handling API requests

  • async: Used to mark a function to be asynchronous
  • await: Put in front of asynchronous calls (i.e fetch) to halt code execution till the awaited request is to be finished

INCLUDE

35 of 46

INCLUDE

Live Demo

36 of 46

INCLUDE

Error Handling

37 of 46

Using Try & Catch

  • try & catch: Used to try out a section of code and catching any errors during the process
  • Good practice to prevent server from failing completely/producing unwanted side-effects

INCLUDE

38 of 46

Asynchronous function with error handling

async function f() {

try {

let response = await fetch(‘http://someurl’)

const data = response.json()

return data;

} catch (err) {

return errorResponse; //with error msg

}

}

39 of 46

Throwing an Error

throw(error): Used to intentionally end a request

  • Typically used with try and catch

INCLUDE

40 of 46

INCLUDE

Creating your own API/server

41 of 46

External Server

Key Libraries for an External Server

express.js: Acts as our server

nodemon: Automatically reloads server on any changes

axios: Used as a safe alternative to JS built-in fetching

cors: Handles access perms to our server

INCLUDE

42 of 46

Next.js Serverless Functions

  • Next.js has a built-in server that we can use through the /api endpoint
    • Makes it so that we don’t need to host our own server & handle all those libraries
  • Will be used for our client project.

INCLUDE

43 of 46

INCLUDE

Postman

44 of 46

What is Postman?

3rd Party Application that allows us to interact with any external or personal server endpoints that we make.

  • This is our main tool for ensuring that the backend is fully functional, so please download it :)
  • Great for testing the code without the browser

INCLUDE

45 of 46

INCLUDE

Live Demo

46 of 46

INCLUDE

Thanks for Coming!

Text me on slack if yg need anything!