Hello precious developers!
Welcome to the Programming and Doodles blog, and today, we are gonna see how APIs work. Note that it’s not about how to work with APIs, which is kind of useless since most of us know how to work with them. What most of us don’t know is how they work behind the scenes.
Let me start by defining the APIs.
What are APIs?
API stands for Application Programming Interface. Sounds fancy, but it’s just another word for “middleman”; in programming at least.
What they do is connect different software systems, enabling them to communicate and work together. Whether you’re booking a flight, streaming music, or checking the weather, it’s these APIs working behind the scenes that make it happen.
If you need to learn more about APIs, this video got you.
But for most of the developers, the question isn’t what is an API. It’s really about how they work.
How APIs work, behind the scenes
For the sake of this tutorial, imagine yourself as a person who needs an Uber taxi ride home. We’d discuss what’s happening throughout the process of requesting a ride through the software application.
#1. Requests
APIs operate through requests, which are opened by the client (your Uber application, that is). In this case, when you open an Uber app, enter your pickup location, and click “Request a Ride“, the application performs the following steps behind the beautiful GUI:
Constructing a request: It creates a structured HTTP request, which includes the HTTP method (like GET, POST, etc), target endpoint URL, Headers for authentication and content types, and finally, the body which includes data sent to the server (like pickup coordinates, final destination, etc.)
Sending the request: These applications often use an HTTP client library like
requests
in Python orfetch
in JS to send requests.
The Developer’s POV
If you are a developer building an API, you’ll define specific endpoints and also set up rules for authentication and validation purposes.
Following is one such basic (—I mean really basic) API route in Python that uses Flask.
Flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/book-ride', methods=['POST'])
def book_ride():
data = request.json
if 'pickup' not in data or 'destination' not in data:
return jsonify({"error": "Invalid request"}), 400
return jsonify({"status": "Ride booked successfully!"}), 200
if __name__ == '__main__':
app.run(debug=True)
#2. Server-side processing
After the client request successfully reaches the server, the API backend processes it by Routing, Processing logic, and integrating.
Routing: The API identifies which endpoint is being retrieved and then calls the corresponding handler (or the function, whatever).
Processing Logic: The server executes the general business logic, like calculating the nearby drivers online or estimating the arrival time. It may also communicate with other APIs or query databases.
Integrations: Most of the APIs often serve as a bridge between multiple systems. Taking a rideshare API for example, it might fetch driver locations from a geolocation, retrieve pricing details from a database, and also call another payment API to authorize the fare.
The Developer’s POV
Following is a sample of code that API developers might use to build the backend logic to handle ride requests, like our use case.
from flask import Flask, request, jsonify
app = Flask(__name__)
# Simulated database
drivers = [
{"id": 1, "location": {"lat": 40.7128, "lon": -74.0060}},
{"id": 2, "location": {"lat": 40.7150, "lon": -74.0100}}
]
@app.route('/nearby-drivers', methods=['GET'])
def get_drivers():
# Extract parameters
lat = float(request.args.get('latitude'))
lon = float(request.args.get('longitude'))
# Filter drivers (mock logic)
nearby_drivers = [driver for driver in drivers if abs(driver['location']['lat'] - lat) < 0.01]
return jsonify(nearby_drivers)
if __name__ == '__main__':
app.run(debug=True)
#3. The Response
Once the server has processed the client request, it sends the final response back to the client. They often have a status code, like 200 OK
, and 404 Not Found.
The rest of the response includes:
Header: Metadata, like content type.
Body: The data payload, typically in JSON Format, which contains the requested information.
The Developer’s POV
For our use case, once a ride is requested, a response like the following would be received from the API:
{
"drivers": [
{"id": 1, "location": {"lat": 40.7128, "lon": -74.0060}},
{"id": 2, "location": {"lat": 40.7150, "lon": -74.0100}}
]
}
And it’s the above data that is displayed beautifully through variables in the GUI of the application, using frontend developer’s magic.
Building an API
Building any API is easy, but building developer-friendly, and reliable APIs needs to ensure best practices such as below.
Authentication and Authorization:
Use tokens (like JWT) or OAuth for secure access.
Rate Limiting:
Prevent abuse by limiting the number of requests per user per minute.
Versioning:
Maintain backward compatibility by versioning endpoints (e.g.,
/v1/book-ride
).
Documentation:
Use tools like Swagger, GitLab, or Postman to document your API for other developers.
Error Handling:
Return meaningful error messages with appropriate status codes.
If you’d love the idea of building an API in Python, just click “yes“ on the poll below:
Wrapping Up
And that’s everything you need to know about APIs. If anything is unclear, you can shoot me an email message me on DM, or just comment below.
Hope you enjoyed it, and until next week, it’s Chenuli Jayasinghe from Programming and Doodles.