Introduction
APIs (Application Programming Interfaces) are the backbone of modern software development, enabling different applications to communicate with each other efficiently. They allow seamless data exchange between systems, automating processes that would otherwise require manual intervention. From fetching real-time weather data to processing payments and integrating third-party services, APIs are essential tools for developers.
In this beginner-friendly guide, we will create a simple API using Python and Flask a lightweight and easy-to-use web framework for Python that allows developers to create APIs and web applications quickly. This API will take a number as input and return some basic properties, such as whether it is even or odd, and its square. We will also deploy the API so that it can be accessed from anywhere.
Understanding APIs
Before diving into the implementation, let’s take a step back and understand APIs at a higher level.
What is an API?
An API acts as a bridge between different software applications, allowing them to communicate with each other. It acts as a middleman, handling requests and responses between a client (like your phone or a website) and a server (where data or services live). For example, you walk into a coffee shop and order a latte. You don’t go behind the counter and make it yourself—you just tell the barista what you want.
Here’s how an API works in this scenario:
- You (the client) order a latte.
- The barista (API) takes your order and communicates it to the kitchen (server).
- The kitchen (server) makes your latte.
- The barista (API) brings it back to you.
You don’t need to know how the coffee is brewed or what machine they use—you just get your latte.
How This Relates to APIs:
- The barista is the API—they handle requests and deliver responses.
- The kitchen is the backend server where all the work happens.
- The customer (you) is the client making a request.
APIs help different apps and services interact without knowing the complex inner workings—just like you don’t need to be a barista to order coffee!
API architectural styles
APIs often use JSON or XML format to send and receive data and APIs can be categorized into various architectural styles, including RESTful APIs, GraphQL APIs, and SOAP APIs.
They also follow a set of rules called HTTP methods, such as::
GET
– Retrieve data.POST
– Send data to create a new resource.PUT
– Update an existing resource.DELETE
– Remove a resource.
In this guide, we will use the GET
method to allow users to request information about a number.
Project Overview
Our API will:
- Accept a number as input via a GET request.
- Check if the number is even or odd.
- Calculate the square of the number.
- Return results in JSON format.
- Be deployed online using Azure App Services.
Prerequisites
Before starting, ensure you have:
- Python 3+ installed.
- Flask installed (
pip install flask
). - A GitHub account to host the project.
- An Azure account for deployment.
Step 1: Setting Up the Project
- Create a project directory:
mkdir simple-api && cd simple-api
- Install Flask:
pip install flask
Step 2: Implementing the API
Create a Python file (app.py
) and add the following code:
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/api/number-info', methods=['GET'])
def number_info():
num = request.args.get('number')
if not num or not num.isdigit():
return jsonify({"error": "Invalid input. Please provide a valid number."}), 400
num = int(num)
response = {
"number": num,
"even_or_odd": "even" if num % 2 == 0 else "odd",
"square": num ** 2
}
return jsonify(response)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
Step 3: Running the API Locally
Save the file and start the API:
python app.py
Test it using:
curl "http://127.0.0.1:5000/api/number-info?number=4"
Expected Response:
{
"number": 4,
"even_or_odd": "even",
"square": 16
}
Step 4: Deploying the API to Azure
You can deploy this API using Azure App Services by following these steps:
- Install Azure CLI:
pip install azure-cli
- Log in to Azure:
az login
- Create a resource group (if not already created):
az group create --name myResourceGroup --location eastus
- Deploy the API directly:
az webapp up --name simple-api --resource-group myResourceGroup --runtime PYTHON:3.8
- Test it using the URL provided:
curl "http://127.0.0.1:5000/api/number-info?number=4"
- (Optional) If using GitHub, push your code to a repository(replace my repo URL with yours):
echo "# pythonapi1" >> README.md
git init
git add README.md
git commit -m "first commit"
git branch -M main
git remote add origin https://github.com/Obs3rve/pythonapi1.git
git push -u origin main
Conclusion
This guide introduced the fundamentals of building an API using Python and Flask. We created a simple API that accepts a number, determines if it is even or odd, and calculates its square. Finally, we deployed it on Azure.
In the next guide, we will enhance this API by allowing it to analyze numbers in more depth. The API will not only check if a number is prime but also return additional interesting mathematical properties about it, along with a fun fact.
Stay tuned for the next guide! 🚀
Author Of article : Chinaza Otumba Read full article