What Is an API? How Apps Talk to Each Other (With an M-Pesa Example)
The Qtec Mastery
Author
When you pay for something with M-Pesa on a website, check the weather on your phone or log in with Google, two pieces of software are talking to each other behind the scenes. If you have wondered what is an API and how that conversation works, this guide is for you. By the end you will understand requests, responses, JSON and status codes, and you will be able to follow how an M-Pesa STK Push payment works from start to finish.
An API (Application Programming Interface) is a set of rules that lets one program ask another program for data or to do something. Your app sends a request, the other system sends back a response, usually in JSON format. |
What is an API in simple terms?
Think of a restaurant. You are the customer, the kitchen is the system that has what you want, and the waiter is the API.
- You do not walk into the kitchen. You give your order to the waiter in a format they understand: "One chapati and beans, please."
- The waiter takes the order to the kitchen, the kitchen prepares it, and the waiter brings it back.
- If the kitchen has run out of beans, the waiter comes back and tells you. That is an error response.
The menu is the API's documentation: it lists what you can ask for and how. The kitchen can change its cooks and equipment without you noticing, as long as the menu stays the same. That is the real power of APIs: systems can work together without knowing how the other one is built inside.
How does a request and response work?
Most web APIs use HTTP, the same protocol your browser uses to load pages. Every request has a few parts:
- URL (endpoint): the address of the thing you want, for example
https://jsonplaceholder.typicode.com/posts/1. - Method: what you want to do, such as get data or create something.
- Headers: extra information, such as the data format or your API key.
- Body: the data you are sending, used when creating or updating.
The response comes back with a status code (did it work?), headers and usually a body containing the data.
What are the main HTTP methods?
| Method | What it does | School portal example |
|---|---|---|
GET | Read data | Get the list of courses |
POST | Create something new | Register a new student |
PUT | Replace a record | Replace a student's full profile |
PATCH | Update part of a record | Change only a student's phone number |
DELETE | Remove something | Delete a draft application |
What does JSON look like?
JSON (JavaScript Object Notation) is the most common format for API data. It is plain text made of keys and values, easy for both people and programs to read. A student record from a school API might look like this:
{
"student_id": 1,
"full_name": "Wanjiku Kamau",
"county": "Nairobi",
"course": {
"course_id": 1,
"course_name": "Web Development",
"fee_kes": 10000.00
},
"enrolled": true
}
Text values go in double quotes, numbers and true/false do not, curly braces hold an object and square brackets hold a list.
Try it yourself: calling a real API with curl
JSONPlaceholder is a free public API made for practice. Open a terminal (Git Bash on Windows works) and run:
curl https://jsonplaceholder.typicode.com/posts/1
You get back a JSON object like this:
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}
The text is placeholder Latin, but the structure is exactly what a real API returns. Now try creating something with POST:
curl -i -X POST https://jsonplaceholder.typicode.com/posts \
-H "Content-Type: application/json" \
-d '{"title": "Hello from Nairobi", "body": "My first API call", "userId": 1}'
The -i flag shows the response headers. You should see 201 Created and your data echoed back with a new id. JSONPlaceholder does not really save it, which makes it safe to experiment with.
What do API status codes mean?
The status code is the first thing to check when something goes wrong. The first digit tells you the category: 2xx success, 4xx your request has a problem, 5xx the server has a problem.
| Code | Meaning | What to do |
|---|---|---|
| 200 OK | Request worked | Use the data in the body |
| 201 Created | New record created | Save the returned ID if you need it |
| 400 Bad Request | Request is malformed | Check your JSON and required fields |
| 401 Unauthorized | Missing or invalid credentials | Check your API key or token |
| 403 Forbidden | Logged in, but not allowed | Check your account's permissions |
| 404 Not Found | The resource does not exist | Check the URL and ID |
| 422 Unprocessable Content | Data failed validation | Fix the fields listed in the error |
| 429 Too Many Requests | You hit a rate limit | Slow down and retry later |
| 500 Internal Server Error | The server failed | Retry later or contact the provider |
What is a REST API?
REST is a popular style for designing web APIs. You do not need the theory to start, just a few habits you will see everywhere:
- URLs name things (resources), methods name actions.
GET /students/5reads student 5,DELETE /students/5removes them. You will not see/getStudentor/deleteStudentin a well-designed REST API. - Each request stands alone. The server does not remember your previous request, so every call carries its own credentials.
- Standard status codes tell you what happened, as in the table above.
Laravel, Django and Express all make it straightforward to build REST APIs, and they usually store the data in a database like the ones in our Databases from Zero series.
What are API keys and why keep them secret?
Most real APIs need to know who is calling. They give you an API key or a set of credentials, which you send with each request, usually in a header. Some, like M-Pesa's Daraja, use credentials to get a short-lived access token first and then send that token with each request.
Treat keys like passwords:
- Store them in a
.envfile on the server, never in frontend JavaScript where anyone can read them. - Never commit them to GitHub. Our Git and GitHub guide shows how to keep
.envout of your repository. - If a key leaks, revoke it and create a new one immediately.
How does M-Pesa STK Push work through an API?
STK Push, officially called "Lipa na M-Pesa Online", is the payment prompt that pops up on a customer's phone asking for their M-Pesa PIN. Safaricom offers it through its Daraja developer platform. Here is the flow, step by step, for a student paying a course fee on a school website:
- Get an access token. Your server sends your app's consumer key and secret (from the Daraja portal) to Safaricom's OAuth endpoint and receives a temporary access token.
- Send the payment request. Your server makes a
POSTrequest with the token, your business shortcode, the amount, the customer's phone number, a reference such as the student ID and your callback URL. - Safaricom acknowledges. It replies straight away to say the request was accepted. This does not mean the customer has paid yet.
- The customer gets the prompt. Brian Otieno's phone shows the payment request. He enters his PIN, cancels or ignores it.
- Safaricom calls your callback URL. When the transaction finishes, Safaricom sends a
POSTrequest to your callback URL with the result: success or failure and, on success, details such as the M-Pesa receipt number. - Your server records the result. On success you save a row in the
paymentstable with the M-Pesa code (for exampleSKA4H7XQ2P), the amount and the time, then mark the fee as paid.
Notice the twist in step 5: for once, Safaricom calls your API. Your callback URL must be a public HTTPS address that accepts JSON, so it cannot be localhost. Daraja provides a sandbox with test credentials so you can build and test the whole flow before going live.
Common mistakes beginners make with APIs
- Trusting the first response. In STK Push, only the callback confirms payment. Never mark a fee as paid on the initial acknowledgement.
- Ignoring status codes. Always check whether the response was 2xx before using the data.
- Putting keys in frontend code. Anything in the browser is public.
- Trusting incoming data blindly. Validate everything your API receives, including callbacks.
Build real APIs, including paymentsIf you want to build server-side systems like this yourself, our online Backend Development programme (8 months, KES 60,000) is the next step. Also useful: Web Development (4 weeks, KES 10,000) |
Frequently asked questions
Is an API the same as a website?No. A website returns pages for people to look at. An API returns data, usually JSON, for programs to use. Many systems have both. Do I need to know a programming language to use an API?Not to try one: curl or a tool like Postman is enough. To use an API inside an app, you need a language such as PHP, Python or JavaScript. Is the M-Pesa Daraja API free to test?Daraja has a sandbox for testing with test credentials. Check Safaricom's Daraja portal for the current requirements to go live. What is the difference between an API key and an access token?An API key is usually long-lived and identifies your app. An access token is short-lived and is issued after you prove who you are, so a leaked token expires quickly. |
Comments (0)
Search Blog
Categories
Popular Posts
Why Traditional Education is Failing Future Developers: The QTEC Approach
326 views
What Is Frontend Development? A Beginner's Guide
121 views
What Is a Database? A Beginner's Guide With Real Kenyan Examples
35 views
Git and GitHub for Beginners: The Commands You Will Actually Use
33 views
Computer Packages Course in Kenya: Fees, Duration and Certificate (2026)
32 views
You Might Also Like
Git and GitHub for Beginners: The Commands You Will Actually Use
Every developer job advert in Kenya expects you to know Git, yet most beginners...
Read More →
How to Become a Web Developer in Kenya With No Experience: Step by Step
You can become a web developer in Kenya without a computer science degree and wi...
Read More →
What Is Frontend Development? A Beginner's Guide
Have you ever visited a website and thought, "Wow, this looks really good"? Mayb...
Read More →