What Is an API? A Simple Explanation for Non-Technical People and Beginners

You use APIs every single day without knowing it. When you check the weather on your phone, pay with Khalti or eSewa, log into a website using your Google account, or book a ride — APIs are making it all work behind the scenes. Yet when someone asks "What is an API?" the typical explanations are filled with jargon that confuses more than it clarifies.
This guide explains APIs in plain language with real-world analogies anyone can understand. If you are a beginner learning to code in Nepal or a business owner trying to understand what your development team is talking about, this article will give you a solid understanding of what APIs are, how they work, and why they matter.
What Exactly Is an API in Simple Terms?
An API (Application Programming Interface) is a messenger that takes your request, tells a system what you want, and delivers the response back to you — like a waiter in a restaurant who connects you to the kitchen.
Imagine you are sitting in a restaurant. You have a menu of food you can order, and the kitchen can prepare that food. But you cannot walk into the kitchen yourself. You need a waiter — someone who takes your order to the kitchen and brings your food back.
An API is that waiter. It sits between two software systems, allowing them to communicate without needing to know how each other works internally.
Real-world example: When you use eSewa to pay for something online in Nepal:
- The shopping website sends a request to eSewa's API: "This customer wants to pay NPR 2,000"
- eSewa's API processes the payment
- The API sends a response back: "Payment successful" or "Payment failed"
- The shopping website shows you the result
The shopping website never sees eSewa's internal code. eSewa never sees the shopping website's code. The API handles all communication between them.
Here is a visual representation:
Your App → API Request → Server/System → API Response → Your App
Example:
Weather App → "What's the weather in Pokhara?" → Weather Server → "28°C, Sunny" → Shows on your screen
How Do APIs Work Technically?
APIs work through a request-response cycle: your application sends a structured request (usually over HTTP) to an API endpoint URL, and the server processes it and returns data in a standard format like JSON.
Let us break down the technical parts:
| Component | What It Is | Restaurant Analogy |
|---|---|---|
| Client | Your app making the request | You (the customer) |
| API Endpoint | The URL you send requests to | The waiter's station |
| Request | What you are asking for | Your food order |
| Server | The system processing your request | The kitchen |
| Response | The data sent back | Your food delivered |
| HTTP Method | The type of action (GET, POST, etc.) | Type of order (dine-in, takeaway) |
| Status Code | Success/error indicator | "Ready" or "Sorry, sold out" |
Here is what an actual API request looks like:
// Fetching weather data for Pokhara using JavaScript
fetch('https://api.openweathermap.org/data/2.5/weather?q=Pokhara&appid=YOUR_KEY')
.then(response => response.json())
.then(data => {
console.log(data.main.temp); // Temperature
console.log(data.weather[0].description); // "clear sky"
});
And the response you get back (in JSON format):
{
"name": "Pokhara",
"main": {
"temp": 301.15,
"humidity": 65
},
"weather": [
{
"description": "clear sky",
"icon": "01d"
}
],
"sys": {
"country": "NP"
}
}
HTTP Methods (the verbs of APIs):
| Method | Purpose | Example |
|---|---|---|
| GET | Retrieve data | Get a list of products |
| POST | Create new data | Add a new user account |
| PUT | Update existing data | Update user profile |
| DELETE | Remove data | Delete a blog post |
| PATCH | Partially update data | Change just the email address |
# Python example using the requests library
import requests
# GET request - fetch data
response = requests.get('https://api.example.com/users')
users = response.json()
# POST request - create new data
new_user = {
"name": "Ram Sharma",
"email": "ram@example.com",
"city": "Pokhara"
}
response = requests.post('https://api.example.com/users', json=new_user)
print(response.status_code) # 201 = Created successfully
What Are the Different Types of APIs?
The four main types of APIs are REST (most common for web), GraphQL (flexible queries), SOAP (enterprise/legacy), and WebSocket (real-time) — as a beginner, focus on learning REST APIs first.
| Type | Best For | Complexity | Usage |
|---|---|---|---|
| REST API | Web and mobile apps | Low-Medium | 80%+ of modern APIs |
| GraphQL | Complex data queries | Medium | Growing (Facebook, GitHub) |
| SOAP | Enterprise, banking | High | Legacy systems |
| WebSocket | Real-time (chat, games) | Medium | Live updates |
| gRPC | Microservices | High | Internal services |
REST API is what you will encounter most often. REST stands for Representational State Transfer, and it uses standard HTTP methods to interact with resources through URLs:
GET /api/products → List all products
GET /api/products/42 → Get product with ID 42
POST /api/products → Create a new product
PUT /api/products/42 → Update product 42
DELETE /api/products/42 → Delete product 42
GraphQL lets the client specify exactly what data it needs:
# REST: You get everything the server sends (even data you don't need)
# GET /api/user/1 returns name, email, address, phone, avatar, etc.
# GraphQL: You ask for exactly what you want
query {
user(id: 1) {
name
email
}
}
# Returns ONLY name and email
For beginners learning web development at Swift Academy, REST APIs are the essential starting point. You will build and consume REST APIs in virtually every web development course.
What Are API Status Codes and What Do They Mean?
Status codes are three-digit numbers in API responses that tell you whether your request succeeded (200s), was redirected (300s), had a client error (400s), or encountered a server error (500s).
| Code | Meaning | What Happened |
|---|---|---|
| 200 | OK | Request succeeded |
| 201 | Created | New resource created successfully |
| 204 | No Content | Success, but nothing to return |
| 301 | Moved Permanently | URL has changed |
| 400 | Bad Request | Your request has errors |
| 401 | Unauthorized | You need to log in |
| 403 | Forbidden | You do not have permission |
| 404 | Not Found | The resource does not exist |
| 429 | Too Many Requests | You hit the rate limit |
| 500 | Internal Server Error | Something broke on the server |
| 503 | Service Unavailable | Server is down or overloaded |
Here is how to handle status codes in your code:
// JavaScript - Handling API responses properly
async function fetchUserData(userId) {
try {
const response = await fetch(`https://api.example.com/users/${userId}`);
if (response.status === 200) {
const data = await response.json();
console.log('User found:', data.name);
return data;
} else if (response.status === 404) {
console.log('User not found');
return null;
} else if (response.status === 401) {
console.log('Please log in first');
// Redirect to login page
} else if (response.status === 500) {
console.log('Server error - try again later');
}
} catch (error) {
console.log('Network error:', error.message);
}
}
# Python - Handling API responses
import requests
response = requests.get('https://api.example.com/users/1')
if response.status_code == 200:
user = response.json()
print(f"Found user: {user['name']}")
elif response.status_code == 404:
print("User not found")
elif response.status_code == 500:
print("Server error, try again later")
What Are Some Real-World API Examples Used in Nepal?
Nepali developers commonly work with payment APIs (Khalti, eSewa), messaging APIs (Sparrow SMS), mapping APIs (Google Maps), and social login APIs (Facebook, Google) to build applications used across Nepal.
| API | Purpose | Used By |
|---|---|---|
| Khalti API | Digital payments | E-commerce sites, apps |
| eSewa API | Digital payments | Online stores, utilities |
| Sparrow SMS API | Send SMS messages | Businesses, OTP verification |
| Nepal Rastra Bank API | Currency exchange rates | Finance apps |
| Google Maps API | Location and mapping | Delivery apps, travel platforms |
| Facebook Login API | Social authentication | Most Nepali apps and websites |
| Firebase API | Authentication, database | Mobile apps |
| Stripe/PayPal API | International payments | Freelancers, SaaS products |
Here is how a Nepali developer might integrate the Khalti payment API:
// Simplified Khalti payment integration example
const khaltiConfig = {
publicKey: "your_khalti_public_key",
productIdentity: "order_12345",
productName: "Online Course - Flutter Development",
productUrl: "https://swiftacademy.com.np/courses/flutter",
amount: 1600000, // Amount in paisa (NPR 16,000)
eventHandler: {
onSuccess(payload) {
// Payment successful
console.log("Payment completed!", payload);
// Verify payment on your server
verifyPayment(payload.token, payload.amount);
},
onError(error) {
console.log("Payment failed:", error);
}
}
};
// Initialize Khalti checkout
const checkout = new KhaltiCheckout(khaltiConfig);
checkout.show({ amount: 1600000 }); // Show payment dialog
# Sending SMS via Sparrow SMS API (Nepal)
import requests
def send_sms(phone_number, message):
url = "http://api.sparrowsms.com/v2/sms/"
payload = {
"token": "your_sparrow_token",
"from": "TheDemo",
"to": phone_number,
"text": message
}
response = requests.post(url, data=payload)
if response.status_code == 200:
print("SMS sent successfully!")
else:
print(f"Failed to send SMS: {response.text}")
# Usage
send_sms("9801234567", "Your OTP is 456789")
How Do You Start Building and Using APIs as a Beginner?
Start by consuming (using) existing APIs with tools like Postman or simple fetch requests, then progress to building your own APIs using frameworks like Express.js (Node.js), Django REST Framework (Python), or Laravel (PHP).
Step 1: Practice with free public APIs
// Try these beginner-friendly free APIs:
// 1. Random joke API
fetch('https://official-joke-api.appspot.com/random_joke')
.then(res => res.json())
.then(joke => console.log(`${joke.setup} - ${joke.punchline}`));
// 2. Random user data
fetch('https://randomuser.me/api/')
.then(res => res.json())
.then(data => console.log(data.results[0].name));
// 3. Country information (Nepal!)
fetch('https://restcountries.com/v3.1/name/nepal')
.then(res => res.json())
.then(data => console.log(data[0].capital)); // Kathmandu
Step 2: Use Postman to test APIs visually
Postman is a free tool that lets you send API requests without writing code. Download it, enter an API URL, choose GET/POST, and see the response. It is the best way to understand APIs before integrating them into your code.
Step 3: Build your own simple API
// Building a simple REST API with Express.js (Node.js)
const express = require('express');
const app = express();
app.use(express.json());
// Sample data
let courses = [
{ id: 1, name: 'Flutter Development', price: 16000 },
{ id: 2, name: 'Next.js Full Stack', price: 16000 },
{ id: 3, name: 'Django Backend', price: 16000 }
];
// GET all courses
app.get('/api/courses', (req, res) => {
res.json(courses);
});
// GET single course
app.get('/api/courses/:id', (req, res) => {
const course = courses.find(c => c.id === parseInt(req.params.id));
if (!course) return res.status(404).json({ message: 'Course not found' });
res.json(course);
});
// POST new course
app.post('/api/courses', (req, res) => {
const course = {
id: courses.length + 1,
name: req.body.name,
price: req.body.price
};
courses.push(course);
res.status(201).json(course);
});
// Start server
app.listen(3000, () => console.log('API running on port 3000'));
# Building a simple REST API with Django REST Framework
# views.py
from rest_framework import viewsets
from rest_framework.response import Response
from .models import Course
from .serializers import CourseSerializer
class CourseViewSet(viewsets.ModelViewSet):
queryset = Course.objects.all()
serializer_class = CourseSerializer
# GET /api/courses/ - list all courses
# GET /api/courses/1/ - get course with id 1
# POST /api/courses/ - create new course
# PUT /api/courses/1/ - update course
# DELETE /api/courses/1/ - delete course
# All handled automatically by ModelViewSet!
What Is API Authentication and Why Does It Matter?
API authentication verifies who is making the request, preventing unauthorized access to data and services — common methods include API keys, OAuth tokens, and JWT (JSON Web Tokens).
| Auth Method | How It Works | Security Level | Use Case |
|---|---|---|---|
| API Key | Unique key in request header | Basic | Public APIs, simple apps |
| OAuth 2.0 | Token-based with login flow | High | Google, Facebook login |
| JWT | Encrypted token with user data | High | Modern web apps |
| Basic Auth | Username/password encoded | Low | Internal tools |
| Bearer Token | Token in Authorization header | Medium-High | Most REST APIs |
// API Key authentication example
fetch('https://api.example.com/data', {
headers: {
'X-API-Key': 'your_api_key_here'
}
});
// JWT authentication example
fetch('https://api.example.com/profile', {
headers: {
'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIs...'
}
});
// OAuth example - Login with Google
// Step 1: User clicks "Login with Google"
// Step 2: Google shows login page
// Step 3: User logs in, Google sends back a code
// Step 4: Your server exchanges the code for a token
// Step 5: Use the token to get user info from Google's API
Never expose API keys in frontend code that users can see. Store sensitive keys on your server and use environment variables:
# .env file (NEVER commit this to GitHub!)
KHALTI_SECRET_KEY=live_secret_key_xxxxx
DATABASE_URL=postgres://user:pass@localhost/db
// Access environment variables safely
const khaltiKey = process.env.KHALTI_SECRET_KEY;
What Reddit and Developer Communities Say About Learning APIs
Discussions on r/learnprogramming, r/webdev, and r/nepal frequently address APIs:
-
"APIs clicked for me when I actually built one." Many developers say that consuming APIs is straightforward, but truly understanding them comes from building your own API from scratch with a framework like Express.js or Django.
-
"Every modern job interview asks about REST APIs." Whether you are applying to a company in Kathmandu or for a remote position, understanding APIs is non-negotiable. It comes up in nearly every technical interview.
-
"The restaurant analogy is overused but it works." Despite being the most common API explanation, community members agree it is effective for that initial "aha" moment before diving into technical details.
-
"Start with Postman before writing code." Postman lets you visually understand request-response cycles without worrying about code syntax, making it the recommended first step for API learning.
Practical Takeaway: Build Your First API Integration Today
Here is a complete, working example you can run right now to understand APIs:
<!-- Save this as api-demo.html and open in a browser -->
<!DOCTYPE html>
<html>
<head>
<title>My First API Call</title>
<style>
body { font-family: Arial; max-width: 600px; margin: 50px auto; }
button { padding: 10px 20px; font-size: 16px; cursor: pointer; }
#result { margin-top: 20px; padding: 15px; background: #f0f0f0; }
</style>
</head>
<body>
<h1>API Demo - Nepal Facts</h1>
<button onclick="getNepalInfo()">Get Nepal Info from API</button>
<div id="result"></div>
<script>
async function getNepalInfo() {
const resultDiv = document.getElementById('result');
resultDiv.innerHTML = 'Loading...';
try {
const response = await fetch('https://restcountries.com/v3.1/name/nepal');
const data = await response.json();
const nepal = data[0];
resultDiv.innerHTML = `
<h3>${nepal.name.common}</h3>
<p>Capital: ${nepal.capital[0]}</p>
<p>Population: ${nepal.population.toLocaleString()}</p>
<p>Region: ${nepal.region}</p>
<p>Languages: ${Object.values(nepal.languages).join(', ')}</p>
<p>Currency: ${Object.values(nepal.currencies)[0].name}</p>
<img src="${nepal.flags.png}" width="200" alt="Nepal Flag">
`;
} catch (error) {
resultDiv.innerHTML = 'Error fetching data: ' + error.message;
}
}
</script>
</body>
</html>
Copy this code, save it as an HTML file, and open it in your browser. Click the button and watch your first API call in action. This is how every app you use works behind the scenes.
Frequently Asked Questions
Do I need to know programming to understand APIs?
You do not need to know programming to understand the concept of APIs. The restaurant analogy and basic understanding of requests and responses is accessible to anyone. However, to actually use APIs in projects, you need basic programming skills in languages like JavaScript or Python. Beginners can start learning APIs within their first month of coding.
Are APIs free to use?
Many APIs offer free tiers with usage limits. For example, Google Maps allows a certain number of free requests per month, and OpenWeatherMap provides free weather data with rate limits. Paid APIs charge based on usage volume. Nepali APIs like Khalti and eSewa are free for merchants to integrate but charge transaction fees on payments.
What is the difference between an API and a website?
A website is designed for humans to view and interact with through a browser. An API is designed for software programs to communicate with each other. When you visit a website, you see a visual page. When software calls an API, it receives raw data (usually in JSON format) that the program then processes and displays however it wants.
How long does it take to learn to work with APIs?
Understanding what APIs are takes an hour. Making your first API call with Postman or fetch takes a day. Building basic API integrations into your projects takes 1-2 weeks. Building your own APIs from scratch requires 1-2 months of learning a backend framework. Courses at Swift Academy cover API development as part of the full-stack curriculum.
What is JSON and why is it important for APIs?
JSON (JavaScript Object Notation) is the most common data format used by APIs to send and receive data. It is human-readable and easy for programming languages to parse. Think of JSON as the "language" that APIs use to communicate — like how English might be the common language between two people who speak different native languages.
Learn to Build APIs at Swift Academy Pokhara
Understanding APIs is essential for every modern developer. At Swift Academy in Pokhara, our Django, Next.js, and Laravel courses teach you to build and consume APIs as part of real-world projects. From payment integrations with Khalti to building your own REST APIs — you will learn by doing. Enroll today for NPR 16,000 per course.
Related Articles
- SQL vs NoSQL Databases: Which Should You Learn First as a Beginner?
- Cloud Computing Basics for Beginners: AWS, Azure, and Google Cloud Explained
- Git and GitHub for Beginners: The Complete Guide Every Developer Needs
Suggested Images
- Hero Image: A diagram showing a mobile phone connecting to a server through an API with labeled arrows — alt text: "How APIs connect applications to servers visual explanation"
- Infographic: The restaurant analogy illustrated with customer, waiter (API), and kitchen (server) — alt text: "API explained using restaurant waiter analogy for beginners"
- Screenshot: Postman interface showing a GET request with JSON response data — alt text: "Postman API testing tool showing request and response"




