What is an API?
An API stands for Application Programming Interface. It is a protocol that allows different software applications to communicate with each other.
In simple terms, an API acts as a middleman that enables two systems to interact with each other, exchange data, and perform specific actions.
An API make the complex process simple and exposes only necessary functionalities to the developers, hiding the internal workings of the system.
For example, when we use Google Maps, that app communicates with Google’s servers using an API. It requests location data, retrieves directions, and displays the results on your device.
If you are not understood yet, we take a real-life example from a non-technology area. Suppose you go into the restaurant for dinner, and then you call the waiter for the menu, then the waiter collects your items and goes to the kitchen, orders to the cook to make those dishes, and after the waiter collects those dishes, comes to the table, serves all the items to you. So in this scenario waiter works like an API.
Why Are APIs Important?
1) Modern Communication: APIs allow different systems to interact efficiently and create modern technology ecosystems.
2) Improved Efficiency: Developers can use APIs to integrate pre-built functions rather than coding from scratch, saving time and resources.
3) Scalability: APIs make it easier to expand functionalities by connecting to external services or platforms.
4) Customization: APIs allow developers to create powerful applications by integrating features from multiple services.
How Do APIs Work?
We learned, API act as a bridge between the client and the server.
Steps in API Communication:
- Request: The client sends a request to the API endpoint (a URL that represents a specific resource).
- Processing: The server processes the request and performs the requested action.
- Response: The API sends back the response in JSON or XML format to the client.
Here’s a basic flow diagram:
- Client (e.g., your app) → API Request → Server → API Response → Client
We covered a proper explanation of the API working process. Click Here
Types of APIs
- Open APIs: Publicly available APIs for external developers. For example: Twitter API.
- Partner APIs: Shared with specific partners to integrate specific features.
- Internal APIs: Used within a company for internal purposes, like linking internal systems.
- Composite APIs: Combine multiple APIs into one call for more efficient processing.
Basic REST API Example
One of the most popular API architectures is REST (Representational State Transfer). RESTful APIs use HTTP methods like:
- GET: To fetch data.
- POST: To create data.
- PUT: To update data.
- DELETE: To delete data.
For example:
Suppose you want to fetch a list of users from an API. The URL for the API endpoint might look like this:
GET https://api.example.com/users
And the API server will return data in JSON format like this:
[
{
"id": 1,
"name": "John Doe",
"email": "john.doe@example.com"
},
{
"id": 2,
"name": "Jane Smith",
"email": "jane.smith@example.com"
}
]
Real-Life Examples of APIs
1) Weather Apps: Use OpenWeatherMap APIs to fetch live weather data like temperature, humidity, etc. Your app sends a request with location info, and the API responds with weather details in real-time.
2) Payment Gateways: Stripe or PayPal expose APIs that allow apps or websites to process payments securely. For example, when you enter card details on an e-commerce site, those details are sent to the API for verification and transaction.
3) Social Media Sharing: Multiple apps use APIs like Instagram and Twitter to post content, fetch user data, or manage media. For example: Use a tool that auto-posts your blog updates to your Facebook page by the Facebook Graph API.
4) Travel Booking: Skyscanner or Cleartrip APIs allow websites to integrate flight, hotel, and car rental searches. Developers connect to these APIs to fetch and display booking options.
Coding Example: Building a Simple API
Here’s how you can create a basic REST API using Python’s Flask framework:
from flask import Flask, jsonify
app = Flask(__name__)
# Sample data
users = [
{"id": 1, "name": "John Doe"},
{"id": 2, "name": "Jane Smith"}
]
@app.route('/api/users', methods=['GET'])
def get_users():
return jsonify(users)
if __name__ == '__main__':
app.run(debug=True)
Explanation of This Code, Line by Line
1) Import Flask and jsonify
from flask import Flask, jsonify
- Flask is a lightweight Python web framework to build APIs and web apps.
- jsonify() converts Python data (List or Dictionaries) to JSON format, which is the standard format for APIs.
2) Create a Flask app instance
app = Flask(__name__)
This code line sets the Flask app and it is the main entry point of your API.
3) Sample Data
users = [
{"id": 1, "name": "John Doe"},
{"id": 2, "name": "Jane Smith"}
]
This is a simple Python list of users, acting as mock database data.
4) Define an API Route
@app.route('/api/users', methods=['GET'])
def get_users():
return jsonify(users)
- /api/users is the endpoint. When someone visits this URL with a GET request, it returns the user data in JSON format.
- jsonify(users) converts the Python list a proper API response.
5) Run the App
if __name__ == '__main__':
app.run(debug=True)
This block of code starts the Flask server at http://127.0.0.1:5000, and the debug=true makes development easier by showing helpful error messages.
How Above Code Works in Real Life?
When you open your browser and visit http://127.0.0.1:5000/api/users, you send a GET request to the Flask API, and the server responds with this:
[
{"id": 1, "name": "John Doe"},
{"id": 2, "name": "Jane Smith"}
]
This is the method of real API work behind the scenes when apps fetch data.