intro-frontend-course

Introduction to APIs

What is an API?

An API (Application Programming Interface) allows one application to interact with another. It’s like a waiter taking your order and bringing back food from the kitchen. For example, when you check the weather on a mobile app, it’s likely using an API to fetch weather data.

Video Explanation:

Resource: What is an API?

Types of APIs

Web APIs: Accessed over the internet using HTTP, they follow a client-server model where requests are sent by the client, and responses are returned by the server.

REST APIs: A subtype of Web APIs that follow RESTful principles. REST (Representational State Transfer) uses HTTP requests for communication and is stateless, meaning each request from a client contains all the information the server needs to fulfill that request. This makes them highly scalable and easier to integrate with web services.

Key Characteristics of REST APIs:

Others:

Video Explanation:

Resource: Types of APIs

Real-World Examples

Common Use Cases

APIs are integral in many services:

Video Explanation:

Understanding HTTP and HTTPS

HTTP Basics

HTTP (Hypertext Transfer Protocol) is the foundation of data communication on the web. It defines how messages are formatted and transmitted, and how web servers and browsers should respond to various commands. HTTP operates as a request-response protocol between a client and server.

HTTPS Basics

HTTPS (Hypertext Transfer Protocol Secure) is the secure version of HTTP. It uses SSL/TLS encryption to secure the data transmitted between the client and server, ensuring that sensitive information like passwords and credit card details remain private.

Key Differences between HTTP and HTTPS:

HTTP Request and Response Bodies

Request Body: The request body contains data sent by the client to the server. This is typically used in methods like POST, PUT, and PATCH. The body can include different formats, such as JSON, XML, or form data.

Example of a Request Body (JSON):

{
  "title": "foo",
  "body": "bar",
  "userId": 1
}

Response Body: The response body contains data sent by the server back to the client. This can be in various formats, including HTML, JSON, or XML.

Example of a Response Body (JSON):

{
  "id": 1,
  "title": "foo",
  "body": "bar",
  "userId": 1
}

HTTP Status Codes and Their Definitions

HTTP status codes indicate the result of the request. Here are some common status codes and their meanings:

Resource: HTTP Status Codes - MDN Web Docs

Handling HTTP Requests with JavaScript

Key Components of a REST API Request

Endpoints and URLs: An endpoint is a specific address where you send requests, usually a URL combined with an HTTP method. For example, https://jsonplaceholder.typicode.com/posts might be an endpoint to get posts data.

HTTP Methods:

Headers: Headers pass additional information with the request or response. Common headers include:

Query Parameters: Used to sort, filter, and paginate resources.

Request Body: Data sent to the server when creating or updating resources, usually in JSON format.

Response Codes: Standard HTTP status codes to indicate the success or failure of a request.

Example of a REST API Request:

fetch('https://jsonplaceholder.typicode.com/posts', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    title: 'foo',
    body: 'bar',
    userId: 1
  })
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

Resource: HTTP Methods and Headers

Error Handling in Fetch Requests

Proper Error Handling

Proper error handling in fetch requests is crucial to deal with network issues or problems with the request. The Fetch API treats even 404 or 500 HTTP status codes as a successful request, so it’s important to explicitly check the response status:

fetch('https://jsonplaceholder.typicode.com/posts')
  .then(response => {
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    return response.json();
  })
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

Resource: Error Handling with Fetch

Working with Headers

Sometimes, you need to send additional information with your requests, like API keys or content types. This is done using headers:

fetch('https://jsonplaceholder.typicode.com/posts', {
  headers: {
    'Content-Type': 'application/json'
  }
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

Resource: Fetch API Headers - MDN Web Docs

JSON: Definition and Importance

What is JSON?

JSON (JavaScript Object Notation) is a lightweight data

interchange format that is easy for humans to read and write and easy for machines to parse and generate. It is text-based and follows a syntax inspired by JavaScript object notation, which makes it familiar to JavaScript developers.

JSON Structure

JSON data is represented in key-value pairs. Here’s a basic example:

{
  "name": "John",
  "age": 30,
  "isStudent": false,
  "courses": ["Math", "Science"],
  "address": {
    "street": "123 Main St",
    "city": "Anytown"
  }
}

Why is JSON Needed?

  1. Interoperability: JSON is language-agnostic and supported by many programming languages, making it an excellent choice for data exchange between different systems.
  2. Simplicity: The syntax is straightforward and easy to learn, reducing the complexity of data representation.
  3. Lightweight: JSON’s compact format ensures that data transmission over the network is efficient.
  4. Readability: Human-readable format makes it easy to understand and debug.
  5. Structure: It supports nested structures, allowing the representation of complex data models.
  6. Flexibility: It can be used for various types of data, including configuration files, API responses, and data storage.

Resource: JSON - MDN Web Docs

Handling JSON Data

Parsing JSON

To convert a JSON string into a JavaScript object, use JSON.parse():

const jsonResponse = '{"name": "John", "age": 30}';
const user = JSON.parse(jsonResponse);
console.log(user.name); // Output: John

Resource: JSON.parse() - MDN Web Docs

Stringifying JSON

To convert a JavaScript object into a JSON string, use JSON.stringify():

const userObject = { name: "John", age: 30 };
const jsonString = JSON.stringify(userObject);
console.log(jsonString); // Output: '{"name":"John","age":30}'

Resource: JSON.stringify() - MDN Web Docs

Asynchronous Patterns

Callbacks:

function getUser(userId, callback) {
  fetch(`https://jsonplaceholder.typicode.com/users/${userId}`)
    .then(response => response.json())
    .then(user => callback(user))
    .catch(error => console.error('Error:', error));
}

getUser(1, user => {
  console.log('User fetched:', user);
});

Promises:

function getUser(userId) {
  return fetch(`https://jsonplaceholder.typicode.com/users/${userId}`)
    .then(response => response.json())
    .then(user => {
      console.log('User fetched:', user);
      return user;
    })
    .catch(error => console.error('Error:', error));
}

getUser(1);

Async/Await:

async function getUser(userId) {
  try {
    const response = await fetch(`https://jsonplaceholder.typicode.com/users/${userId}`);
    const user = await response.json();
    console.log('User fetched:', user);
  } catch (error) {
    console.error('Error:', error);
  }
}

getUser(1);

Resource: Async/Await - MDN Web Docs

Error Handling Strategies

async function safeGetUser(userId) {
  try {
    const user = await getUser(userId);
    return user;
  } catch (error) {
    console.error('Failed to fetch user:', error);
    return { name: 'Default User', age: 0 };
  }
}

Resource: Error Handling in Async Functions

Conclusion

APIs are the glue that connects different software applications, enabling you to leverage external data and functionality in your projects. They open up a world of possibilities in web development. Understanding HTTP and HTTPS, handling requests and responses, and managing errors effectively are crucial skills for any web developer.