Advanced Web Application Light
Advanced Web Application Light
Frameworks ...................................................................................................................... 14
In recent years, there has been a significant shift in the front-end development landscape.
The rise of new technologies, such as React, Vue, and Svelte, has made it possible to build
more dynamic and interactive web applications than ever before.
These technologies are all based on the concept of reactivity, which means that the user
interface can automatically update whenever the underlying data changes. This makes it
possible to create fluid and responsive web applications that provide a great user
experience.
In this module, we will introduce you to the fundamentals of front-end development, with a
focus on reactivity and the modern web. We will cover the following topics:
3
Front-end Development
Front-end developers are responsible for creating a user interface that is both visually
appealing and easy to use. They work closely with designers and back-end developers to
ensure that the website or application meets the needs of the users.
Improve the user experience: A well-designed front-end can make it easier for users to
find the information they need and complete tasks.
Increase conversions: A visually appealing and user-friendly front-end can encourage
users to stay on the website or application longer and make purchases.
Boost SEO: A responsive and well-coded front-end can help a website rank higher in
search engine results pages (SERPs).
The core technologies of front-end development are HTML, CSS, and JavaScript.
HTML (HyperText Markup Language) is used to define the structure of a web page.
CSS (Cascading Style Sheets) is used to style the web page.
JavaScript is used to add interactivity to the web page.
Front-end developers use these technologies to create web pages that are both visually
appealing and functional.
In recent years, there has been a significant shift in the front-end development landscape.
The rise of new technologies, such as React, Vue, and Svelte, has made it possible to build
more dynamic and interactive web applications than ever before.
These technologies are all based on the concept of reactivity, which means that the user
interface can automatically update whenever the underlying data changes. This makes it
possible to create fluid and responsive web applications that provide a great user
4
experience.
In addition to reactive technologies, front-end developers are also using modern CSS
frameworks, such as Bootstrap and Tailwind CSS, to create responsive and mobile-friendly
web applications.
Front-end developers need to have a strong understanding of HTML, CSS, and JavaScript.
They also need to be familiar with modern front-end technologies, such as React, Vue, and
Svelte.
In addition to technical skills, front-end developers also need to have good design skills and
be able to think creatively. They need to be able to understand the needs of the users and
design a user interface that is both visually appealing and easy to use.
The future of front-end development is bright. As new technologies emerge and existing
technologies continue to improve, front-end developers will be able to create even more
dynamic and interactive web applications.
Here are some of the trends that are shaping the future of front-end development:
The rise of artificial intelligence (AI): AI is being used to develop new tools and
technologies that can help front-end developers to be more productive and efficient.
The increasing popularity of progressive web apps (PWAs): PWAs are web applications
that can be installed on a user's device and provide a native app-like experience.
Front-end developers are increasingly being asked to build PWAs.
The growing importance of accessibility: Front-end developers are increasingly being
asked to build web applications that are accessible to users with disabilities.
5
Front-end Frameworks
Front-end frameworks are essential tools for developing user interfaces (UIs) for web
applications. They provide a structured and standardized approach to building UI
components, making it easier to create consistent and maintainable code. For BSIT students,
it is crucial to understand the different front-end frameworks available and their suitability
for various types of projects.
React: React is a JavaScript library for building user interfaces. It is known for its
component-based approach, making it easy to create modular and reusable UI
components. React is widely used for developing Single-Page Applications (SPAs) and
dynamic web applications.
Vue.js: Vue.js is another popular JavaScript framework for building UIs. It is similar to
React in many ways but offers a more lightweight and approachable syntax. Vue.js is
well-suited for smaller projects and applications that require a quick development
turnaround.
Svelte: Svelte is a relatively new JavaScript framework that has gained traction in
recent years. It differs from React and Vue.js in its compile-time reactivity, which
means the framework handles reactivity more efficiently, leading to faster
performance. Svelte is a promising choice for building performant web applications.
6
Framework
Several factors should be considered when choosing a front-end framework:
Project requirements: The specific requirements of the project should dictate the
choice of framework. For instance, if the project involves building a complex SPA,
React or Angular might be suitable. For smaller projects or rapid prototyping, Vue.js or
Svelte could be better choices.
Developer experience: The framework's learning curve and ease of use should be
considered. You should choose a framework that aligns with your experience level and
learning preferences.
Community and support: A large and active community around the framework can
provide valuable resources, documentation, and support during development.
7
Setting Up Environment
Extensions
Icons
You can install Material Icon Theme it supports almost every file extension and can be
customized for everyone's needs.
Automatically rename paired HTML/XML tag, same as Visual Studio IDE does.
Automatically add HTML/XML close tag, same as Visual Studio IDE or Sublime Text does.
A basic spell checker that works well with code and documents. The goal of this spell
checker is to help catch common spelling errors while keeping the number of false positives
low.
Error Lens
ErrorLens turbocharges language diagnostic features by making diagnostics stand out more
prominently, highlighting the entire line wherever a diagnostic is generated by the language
and also prints the message inline.
ESLint
8
GitLens
GitLens supercharges Git inside VS Code and unlocks untapped knowledge within each
repository. It helps you to visualize code authorship at a glance via Git blame annotations
and CodeLens, seamlessly navigate and explore Git repositories, gain valuable insights via
rich visualizations and powerful comparison commands, and so much more.
Import Cost
This extension will display inline in the editor the size of the imported package. The
extension utilizes webpack in order to detect the imported size.
Prettier is an opinionated code formatter. It enforces a consistent style by parsing your code
and re-printing it with its own rules that take the maximum line length into account,
wrapping code when necessary.
The extension provides syntax highlighting, TypeScript support, and intellisense for template
expressions and component props.
9
Module 2 - Introduction to Vite
Why Vite?
The Problems
Before ES modules were available in browsers, developers had no way to write JavaScript in
a modularized fashion. This is why bundling tools were created. These tools crawl, process,
and concatenate our source modules into files that can run in the browser.
Over time, tools like webpack, Rollup, and Parcel have greatly improved the development
experience for frontend developers. However, as we build more and more complex
applications, the amount of JavaScript we use is also increasing dramatically. It is not
uncommon for large-scale projects to contain thousands of modules.
This is starting to cause performance bottlenecks for JavaScript-based tooling. It can often
take an unreasonably long time (sometimes up to minutes!) to spin up a dev server, and
even with Hot Module Replacement (HMR), file edits can take a couple of seconds to be
reflected in the browser. This slow feedback loop can greatly affect developers' productivity
and happiness.
Vite aims to address these issues by taking advantage of two new advancements in the
ecosystem:
This allows Vite to be much faster than previous bundling tools, especially for large-scale
projects.
When you start the development server for the first time, a traditional bundler has to crawl
through and build your entire application before it can start serving it. This can be slow,
especially for large projects with many dependencies.
Vite improves the development server start time by dividing the modules in your application
into two categories: dependencies and source code.
Dependencies are mostly plain JavaScript that doesn't change often during
development. Vite pre-bundles dependencies using esbuild, which is a very fast tool
10
written in Go. This means that Vite can start serving your application much faster than
a traditional bundler.
Source code often contains non-plain JavaScript that needs to be transformed (e.g.
JSX, CSS, or Vue/Svelte components). It also changes more often than dependencies.
Vite serves source code over native ESM, which means that the browser can help with
some of the bundling work. This makes Vite even faster for development, especially
for large projects with a lot of source code.
Slow Updates
Traditional bundlers are inefficient at rebuilding the bundle when a file is edited. This is
because they have to rebuild the entire bundle, even if only a small part of the application
has changed. This can lead to slow update speeds, especially for large applications.
Some bundlers support Hot Module Replacement (HMR), which allows modules to be
replaced without reloading the entire page. This can improve the development experience,
but HMR update speed can still deteriorate as the size of the application grows.
Vite uses native ESM to perform HMR. This means that Vite can only invalidate the chain
between the edited module and its closest HMR boundary, which is usually just the module
itself. This makes HMR updates consistently fast, regardless of the size of the application.
Vite also leverages HTTP headers to speed up full page reloads. This means that Vite can let
the browser do more of the work, such as caching dependency modules. This makes Vite
even faster for development, especially for large applications.
Overall, Vite is a much faster and more efficient bundler than traditional bundlers. This
makes it a great choice for developing large and complex web applications.
11
Vite as a bundler
Overview
Vite (French word for "quick", pronounced /vit/, like "veet") is a new build tool that aims to
make web development faster and easier. It has two main parts:
A development server that provides rich features over native ES modules, such as
extremely fast Hot Module Replacement (HMR).
A build command that bundles your code with Rollup to produce highly optimized
static assets for production.
Vite is opinionated and comes with sensible defaults out of the box, but it is also highly
extensible via plugins and a JavaScript API with full typing support.
We will be utilizing Node Version Manager (NVM) to effectively manage and switch between
different versions of the Node.js runtime environment.
nvm -v
You should see the version of nvm, if not then verify your installation.
To check the list of currently install node versions, just run nvm list
This will display all available versions, for first time user you will see an empty records.
12
To install a specific node version, just run nvm install <specific version number>
After executing the command, it will install that version of node.js. To verify just execute
again the command nvm list
20.9.0
However, it is currently not activated. To activate, just run nvm use <install version
number>
You will notice an asterisk (*) before the version number. This indicates that the version is
currently being used.
> node -v
v20.9.0
13
Module 3 - Introduction to
Single Page Application (SPA)
with Frontend Frameworks
To develop SPAs effectively, frontend frameworks have emerged as essential tools. These
frameworks provide a structured approach to building complex client-side applications,
simplifying the development process and enhancing maintainability. Popular frontend
frameworks include React, Angular, and Vue.js.
14
Core Concepts of SPAs
Understanding the core concepts of SPAs is crucial for building effective web applications.
Key concepts include:
1. Client-side rendering: SPAs render the user interface on the client-side using
JavaScript, reducing the load on the server and improving responsiveness.
2. Single HTML document: SPAs load a single HTML document and dynamically update
the content, eliminating page reloads and creating a seamless user experience.
3. JavaScript routing: SPAs utilize JavaScript routing to handle navigation between
different sections of the application without reloading the page.
4. Data fetching and manipulation: SPAs fetch and manipulate data using JavaScript
APIs, such as Fetch or Axios, to update the application's state and render the
appropriate UI components.
Benefits of SPAs
SPAs offer several advantages over traditional MPAs, including:
1. Enhanced user experience: SPAs provide a more responsive and fluid user
experience, similar to native mobile applications.
2. Faster page load times: By eliminating full page reloads, SPAs can significantly
reduce page load times, improving user engagement.
3. Improved scalability: SPAs can handle large amounts of data and complex user
interactions efficiently.
4. Richer interactions: SPAs enable more interactive and dynamic user experiences,
such as real-time data updates and animations.
15
simplifying development and maintenance.
16
Frontend Exploration
React
What is React?
React is a JavaScript library for building user interfaces (UIs). It is declarative, efficient, and
flexible, making it a popular choice for developing single-page applications (SPAs). React
was created by Jordan Walke, a software engineer at Facebook, and is maintained by
Facebook and a community of individual developers and companies.
Describing the UI
UI is built from small units like buttons, text, and images. React lets you combine them into
reusable, nestable components. From websites to phone apps, everything on the screen can
be broken down into components. In this chapter, you’ll learn to create, customize, and
conditionally display React components.
React applications are built from isolated pieces of UI called components. A React
component is a JavaScript function that you can sprinkle with markup. Components can be
as small as a button, or as large as an entire page. Here is a Gallery component rendering
three Profile components:
17
function Profile() {
return (
<img
src="https://i.imgur.com/MK3eW3As.jpg"
alt="Katherine Johnson"
/>
);
}
You can declare many components in one file, but large files can get difficult to navigate. To
solve this, you can export a component into its own file, and then import that component
from another file:
// Gallery.js
import Profile from './Profile.js';
18
// Profile.js
export default function Profile() {
return (
<img
src="https://i.imgur.com/QIrZWGIs.jpg"
alt="Alan L. Hart"
/>
);
}
Vue
What is Vue
Vue (pronounced /vjuː/, like view) is a JavaScript framework for building user interfaces. It
builds on top of standard HTML, CSS, and JavaScript and provides a declarative and
component-based programming model that helps you efficiently develop user interfaces, be
they simple or complex.
createApp({
setup() {
return {
count: ref(0)
}
}
}).mount('#app')
<div id="app">
<button @click="count++">
Count is: {{ count }}
</button>
</div>
Declarative Rendering: Vue extends standard HTML with a template syntax that
19
allows us to declaratively describe HTML output based on JavaScript state.
Reactivity: Vue automatically tracks JavaScript state changes and efficiently updates
the DOM when changes happen.
Vue is a framework and ecosystem that covers most of the common features needed in
frontend development. But the web is extremely diverse - the things we build on the web
may vary drastically in form and scale. With that in mind, Vue is designed to be flexible and
incrementally adoptable. Depending on your use case, Vue can be used in different ways:
Single-File Components
In most build-tool-enabled Vue projects, Vue components using an HTML-like file format
called Single-File Component (also known as *.vue files, abbreviated as SFC). A Vue SFC, as
the name suggests, encapsulates the component's logic (JavaScript), template (HTML), and
styles (CSS) in a single file. Here's the previous example, written in SFC format:
<script setup>
import { ref } from 'vue'
const count = ref(0)
</script>
<template>
<button @click="count++">Count is: {{ count }}</button>
</template>
<style scoped>
button {
font-weight: bold;
}
</style>
SFC is a defining feature of Vue and is the recommended way to author Vue components if
your use case warrants a build setup.
20
Svelte
What is Svelte
Svelte is a tool for building web applications. Like other user interface frameworks, it allows
you to build your app declaratively out of components that combine markup, styles and
behaviours.
These components are compiled into small, efficient JavaScript modules that eliminate
overhead traditionally associated with UI frameworks.
You can build your entire app with Svelte (for example, using an application framework like
SvelteKit), or you can add it incrementally to an existing codebase. You can also ship
components as standalone packages that work anywhere.
Adding data
A component that just renders some static markup isn't very interesting. Let's add some
data.
First, add a script tag to your component and declare a name variable:
// App.svelte
<script>
let name = 'Svelte';
</script>
<h1>Hello World!</h1>
// App.svelte
<h1>Hello {name}!</h1>
Inside the curly braces, we can put any JavaScript we want. Try changing name to
name.toUpperCase() for a shoutier greeting.
21
// App.svelte
<h1>Hello {name.toUpperCase()}!</h1>
22
UI Development with Vue
cd vue-project
yarn
yarn dev
Done in 210.31s.
Make sure to enter your project name, vue as a framework and Javascript as a variant. Then
run the following commands
23
> cd vue-project
> yarn
> yarn dev
node_modules: This directory contains all the third-party dependencies installed for your
Vue project. It's managed by Node Package Manager (npm) or Yarn and should not be
modified manually.
public: This directory holds static assets like images, fonts, and other files that will be
directly served by the web server. These files are not bundled into the main JavaScript
application.
src: This directory contains the source code for your Vue application. It includes
components, router configuration, store, and other JavaScript files that define the
functionality and behavior of your app.
.gitignore: This file specifies which files and directories should be ignored by Git version
control. It prevents unnecessary files from being tracked and avoids clutter in your
repository.
index.html: This file serves as the entry point for your web application. It defines the basic
HTML structure of your app and includes the main JavaScript bundle generated by Vue.
package.json: This file contains metadata about your project, including its name, version,
dependencies, and scripts. It's used by npm and Yarn to manage dependencies and run
project commands.
README.md: This file provides documentation about your project, explaining its purpose,
usage, and installation instructions. It serves as a reference for new contributors and users.
vite.config.js: This file configures Vite, the Vue build tool, for your project. It specifies
24
options like server settings, file processing, and dependency resolution.
yarn.lock: This file is generated by Yarn and contains a lockfile that ensures consistent
dependencies across different environments. It prevents dependency conflicts and ensures
the same versions of libraries are used.
The App.vue
<template>
</template>
+ <script setup>
+ </script>
<template>
</template>
The <script setup> tag is a new syntax introduced in Vue 3.3 for using the Composition
API inside Single-File Components (SFCs). It is the recommended syntax if you are using
both SFCs and Composition API.
Conditional Rendering
The directive v-if is used to conditionally render a block. The block will only be rendered if
the directive's expression returns a truthy value.
For example,
25
<script setup>
</script>
<template>
+ <h1 v-if="true">True</h1>
</template>
You can use the v-else directive to indicate an "else block" for v-if:
<script setup>
</script>
<template>
<h1 v-if="true">True</h1>
+ <h1 v-else>False</h1>
</template>
The v-else-if, as the name suggests, serves as an "else if block" for v-if. It can also be
chained multiple times:
<script setup>
</script>
<template>
<h1 v-if="true">True</h1>
+ <h1 v-else-if="true & true">True & True</h1>
+ <h1 v-else-if="true & false">True & False</h1>
<h1 v-else>False</h1>
</template>
Another option for conditionally displaying an element is the v-show directive. The usage is
largely the same:
26
<script setup>
</script>
<template>
<h1 v-if="true">True</h1>
<h1 v-else-if="true & true">True & True</h1>
<h1 v-else-if="true & false">True & False</h1>
<h1 v-else>False</h1>
+ <h1 v-show="true">Using Show</h1>
</template>
v-if vs v-show
v-if is "real" conditional rendering because it ensures that event listeners and child
components inside the conditional block are properly destroyed and re-created during
toggles.
v-if is also lazy: if the condition is false on initial render, it will not do anything - the
conditional block won't be rendered until the condition becomes true for the first time.
In comparison, v-show is much simpler - the element is always rendered regardless of initial
condition, with CSS-based toggling.
Generally speaking, v-if has higher toggle costs while v-show has higher initial render costs.
So prefer v-show if you need to toggle something very often, and prefer v-if if the condition
is unlikely to change at runtime.
List Rendering
We can use the v-for directive to render a list of items based on an array. The v-for directive
requires a special syntax in the form of item in items, where items is the source data array
and item is an alias for the array element being iterated on:
<script setup>
</script>
<template>
// item in items
<li v-for="number in [1, 2, 3, 4]">
{{ number }}
</li>
</template>
27
Single File Component
Inside src folder, create another file named BaseButton.vue then insert the following
code. It is recommended to name your component with multi-word.
// BaseButton.vue
<script setup>
</script>
<template>
<button>Click me</button>
</template>
// App.vue
<script setup>
import BaseButton from './BaseButton.vue'
</script>
<template>
<BaseButton></BaseButton>
</template>
Reactivity
Using ref Function in Vue with script setup
The ref function is an essential tool in the Composition API when working with script setup in
Vue. It allows you to create reactive references for various data types, including DOM
elements, reactive objects, and primitive values.
<script setup>
import { ref } from 'vue';
</script>
2. Declare and Define: Use ref with the desired initial value:
28
const myRef = ref(42); // Declare a ref with initial value of 42
const textRef = ref('Initial text'); // Ref for a string
Template: Inside the template, you can directly access the ref's unwrapped value
using its name:
<template>
<p>{{ myRef }}</p>
</template>
<script setup>
const double = () => myRef.value * 2;
</script>
<template>
<input v-model="textRef" type="text"/>
</template>
<script setup>
const updateValue = () => {
myRef.value = 50;
};
</script>
Template Refs:
29
Use ref with a template ref for DOM elements:
<template>
<input ref="myInput" type="text"/>
</template>
<script setup>
const myInput = ref(null);
// Access DOM element properties
myInput.value.focus();
</script>
30
Using Vue Router
Vue Router is a popular routing library for Vue.js applications. It allows you to easily manage
navigation between different views in your application.
Example
In Vue 3 using script setup, it's recommended to create a separate router.js file to manage
the router configuration. This approach promotes code organization and separation of
concerns, making the main.js file more concise and focused on initializing the Vue
application.
1. Create a separate router.js file inside src directory, then copy and paste the following
code.
const routes = [
{
path: '/',
name: 'home',
component: () => import('./components/Home.vue'),
},
];
This code defines a single route: '/' (home page). The component property for each route
specifies the respective Vue component to render when that route is active.
2. Create a component named Home.vue inside components folder then paste the
following code
31
<template>
Home page
</template>
- createApp(App).mount('#app')
+ let app = createApp(App)
+ app.use(router)
+ app.mount('#app')
<template>
<router-view></router-view>
</template>
5. Run the app then check. It will load our Home.vue component when you access the
root path that is '/'
32
Project Development
We are going to build a sample project using Vue. Before to do that, let's clear some codes.
In App.vue, copy the following code snippet.
// App.vue
<script setup>
</script>
<template>
</template>
33
reverse</option>
</select>
</div>
<div class="form-group">
<label>Flex Wrap:</label>
<select class="form-select" v-model="flexWrap">
<option value="">-- Please select --</option>
<option value="flex-nowrap">nowrap</option>
<option value="flex-wrap">wrap</option>
<option value="flex-wrap-reverse">wrap-
reverse</option>
</select>
</div>
<div class="form-group">
<label>Justify Content:</label>
<select class="form-select" v-
model="flexJustifyContent">
<option value="">-- Please select --</option>
<option value="justify-content-start">flex-
start</option>
<option value="justify-content-end">flex-
end</option>
<option value="justify-content-
center">center</option>
<option value="justify-content-around">space-
around</option>
<option value="justify-content-evenly">space-
evenly</option>
<option value="justify-content-between">space-
between</option>
</select>
</div>
<div class="form-group">
<label>Align Items:</label>
<select class="form-select" v-model="flexAlignItems">
<option value="">-- Please select --</option>
<option value="align-items-stretch">stretch</option>
<option value="align-items-
baseline">baseline</option>
<option value="align-items-center">center</option>
<option value="align-items-start">flex-
start</option>
<option value="align-items-end">flex-end</option>
</select>
</div>
<div class="form-group">
34
<label>Align Content:</label>
<select class="form-select" v-model="flexContent">
<option value="">-- Please select --</option>
<option value="align-content-center">center</option>
<option value="align-content-start">flex-
start</option>
<option value="align-content-end">flex-end</option>
<option value="align-content-around">space-
around</option>
<option value="align-content-evenly">space-
evenly</option>
<option value="align-content-between">space-
between</option>
</select>
</div>
<div class="mt-5">
<div style="width: 100%; height: 400px;"
class="bg-primary bg-opacity-10 d-flex border
border-4 border-warning" :class="flexClass">
<div v-for="child in childCount" :key="child"
class="p-5 bg-primary text-center d-flex align-
items-center justify-content-center fs-1 text-white border border-2
border-dark">
{{ child }}
</div>
</div>
</div>
</div>
</div>
</div>
The template starts with a container div with classes container, py-5, and an inline
style setting the height to 100vh (full view height).
Inside the container, there's a row div for horizontal layout with two child col divs.
Flexbox Controls:
The first column (col-md-4) contains a card displaying information about Flexbox.
The second column (col-md-8) holds several form elements for controlling various
Flexbox properties:
Child Count: Input field for specifying the number of child elements to display in the
Flexbox container.
Flex Direction: Select box for choosing the direction of the flex lines (row, column,
etc.).
Flex Wrap: Select box for setting how flex lines wrap (nowrap, wrap, etc.).
35
Justify Content: Select box for controlling the alignment of flex items along the main
axis.
Align Items: Select box for controlling the alignment of flex items along the cross axis.
Align Content: Select box for controlling the alignment of flex lines along the cross
axis.
Flexbox Preview:
The template utilizes several Vue features for data binding and dynamic rendering:
v-model directive binds the form elements to corresponding data properties
(childCount, flexDirection, etc.).
:class directive dynamically adds classes to the flexbox container based on the
selected options.
v-for directive iterates over the childCount and renders the corresponding number of
child elements.
36
import { ref, computed } from 'vue'
This Vue script defines the data and computed properties used by the previously added html
template. Let's break down the code:
Imports:
Data Properties:
childCount: ref variable holding the number of child elements (initially set to 1).
flexDirection: ref variable holding the selected flex direction (initially empty).
flexWrap: ref variable holding the selected flex wrap behavior (initially empty).
flexJustifyContent: ref variable holding the selected justification option (initially
empty).
flexAlignItems: ref variable holding the selected alignment option for items (initially
empty).
flexContent: ref variable holding the selected alignment option for content (initially
empty).
Computed Property:
flexClass: computed property that dynamically generates the class string based on
selected options.
37
flexClass
Run the project using yarn dev then try the output.
38
Module 4 - Application
Programming Interface
Application Programming Interfaces (APIs) have become indispensable tools for software
development and integration. APIs provide a structured and standardized way for different
applications to communicate and exchange data, enabling seamless integration and
innovation across the digital landscape. This module delves into the fundamentals of APIs,
exploring their concepts, functionalities, and real-world applications.
39
What is API?
An API (Application Programming Interface) is a set of rules and specifications that define
how two software applications can communicate with each other. It acts as an intermediary,
translating requests from one application into understandable instructions for the other,
allowing them to exchange data and functionality. APIs are the backbone of modern
software development, facilitating data sharing, integration, and innovation.
Types of APIs
Public APIs: Public APIs are freely accessible and documented, allowing anyone to
build applications that interact with the API's provided services or data.
Private APIs: Private APIs are restricted to authorized users or applications within an
organization or ecosystem.
Partner APIs: Partner APIs are designed for specific partners or collaborators,
enabling them to integrate their applications or services with the API provider's
platform.
API Lifecycle
The API lifecycle encompasses the entire process of creating, maintaining, and evolving an
API to ensure its effectiveness and relevance.
Design and Planning: Defining the API's purpose, target audience, and functional
scope.
Development and Implementation: Creating the API's code, documentation, and
testing infrastructure.
Deployment and Access: Publishing the API for public or restricted access.
Maintenance and Evolution: Monitoring API usage, addressing bugs, and
implementing new features or enhancements.
40
Benefits of Utilizing APIs
Accelerated Development: APIs provide pre-built functionalities, reducing
development time and effort.
Enhanced Integration: APIs enable seamless integration between different
applications and systems.
Innovation and Collaboration: APIs foster innovation by enabling developers to
build upon existing services and data.
Scalability and Flexibility: APIs facilitate scalable and flexible solutions that can
adapt to changing requirements.
41
Using public API
JSONPlaceholder is a free online REST API that provides a vast collection of fake data for
testing and prototyping purposes. It offers a variety of resources, including posts,
comments, albums, photos, todos, and users, making it an ideal tool for practicing API
interactions and data manipulation in JavaScript. This is the url
https://jsonplaceholder.typicode.com/
fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json())
.then(data =>
console.log(data))
.catch(error =>
console.error(error)
);
This code snippet initiates a GET request to the /posts endpoint of the JSONPlaceholder API.
The response is then parsed as JSON data, and the resulting data object is logged to the
console.
42
const newPost = {
title: 'My New Post',
body: 'This is the content of my new post.',
};
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
body: JSON.stringify(newPost),
headers: {
'Content-Type': 'application/json',
},
})
.then(response => response.json())
.then(data =>
console.log(data))
.catch(error =>
console.error(error));
Similarly, to update an existing post, you would use the PUT method and specify the ID of
the post to update:
const updatedPost = {
id: 1, // ID of the post to update
title: 'Updated Title',
body: 'Updated post content.',
};
fetch(`https://jsonplaceholder.typicode.com/posts/${updatedPost.id}`, {
method: 'PUT',
body: JSON.stringify(updatedPost),
headers: {
'Content-Type': 'application/json',
},
})
.then(response => response.json())
.then(data =>
console.log(data))
.catch(error =>
console.error(error)
);
Finally, to delete a post, you can use the DELETE method and specify the ID of the post to
43
delete:
fetch(`https://jsonplaceholder.typicode.com/posts/${postId}`, {
method: 'DELETE',
})
.then(response => console.log(response.status))
.catch(error => console.error(error));
44
Module 5 - Deployment to Vercel
from Github
1. Prerequisites:
Vercel will automatically detect your Vue.js project and pre-configure the
deployment settings.
You can review and adjust settings like the build command, environment
variables, and custom domains (optional).
Make sure the "Build command" field is set to npm run build or yarn build
depending on your project setup.
Any future changes pushed to your Github repository will automatically trigger a
new deployment on Vercel.
Vercel also offers integrations with CI/CD tools like Travis CI and CircleCI for
automated builds and deployments.
45