API – Expert Network Consultant https://www.expertnetworkconsultant.com Networking | Cloud | DevOps | IaC Thu, 27 Apr 2023 10:56:55 +0000 en-GB hourly 1 https://wordpress.org/?v=6.3.5 Build and understand APIs with Python: A Comprehensive Step by Step Walkthrough https://www.expertnetworkconsultant.com/python-programming-foundations-for-the-network-engineer/build-and-understand-apis-with-python-a-comprehensive-step-by-step-walkthrough/ Mon, 01 May 2023 00:01:52 +0000 http://www.expertnetworkconsultant.com/?p=6173 Continue readingBuild and understand APIs with Python: A Comprehensive Step by Step Walkthrough]]> An API (Application Programming Interface) is a set of rules that define how different software components should interact with each other. The most common way of communicating with an API is through HTTP requests.

HTTP (HyperText Transfer Protocol) is a protocol used to transfer data over the internet. It has several methods, including GET, POST, PUT, and DELETE, which are used to perform specific actions on a resource.

To demonstrate this, we will use Flask, a Python web framework, to create a simple API with four endpoints that correspond to these HTTP methods.

The API has a simple data store consisting of three key-value pairs. Here are the endpoints and their corresponding HTTP methods:

GET method at /api to retrieve all the data from the API (Read)
POST method at /api to submit new data to the API (Create)
PUT method at /api/ to update an existing data item in the API by providing its ID (Update)
DELETE method at /api/ to delete an existing data item in the API by providing its ID (Delete)

In the example code provided, we have a simple API built with Python’s Flask framework. The API has a data store consisting of three key-value pairs. We have defined four API endpoints, one for each HTTP method, which correspond to the different CRUD (Create, Read, Update, Delete) operations that can be performed on the data store.

client and server api http request methods

The URL is the location where we can access our API, typically consisting of three components:

Protocol: denoting the communication protocol such as http:// or https://.

Domain: the server name that hosts the API, spanning from the protocol to the end of the domain extension (e.g., .com, .org, etc.). As an illustration, the domain for my website is expertnetworkconsultant.com.

Endpoint: equivalent to the pages on a website (/blog, /legal), an API can have multiple endpoints, each serving a distinct purpose. When designing an API with Python, it’s essential to define endpoints that accurately represent the underlying functionality of the API.

To test these endpoints, we can use the command-line tool cURL, or write Python code using the requests library. In the code examples provided, we use Python requests to send HTTP requests to the API endpoints and handle the responses.

Create an API with FLASK

from flask import Flask, jsonify, request

app = Flask(__name__)

# Data store for the API
data = {
    '1': 'John',
    '2': 'Mary',
    '3': 'Tom'
}

# GET method to retrieve data from the API
@app.route('/api', methods=['GET'])
def get_data():
    return jsonify(data)

# POST method to submit data to the API
@app.route('/api', methods=['POST'])
def add_data():
    req_data = request.get_json()
    data.update(req_data)
    return jsonify(req_data)

# PUT method to update data in the API
@app.route('/api/', methods=['PUT'])
def update_data(id):
    req_data = request.get_json()
    data[id] = req_data['name']
    return jsonify(req_data)

# DELETE method to delete data from the API
@app.route('/api/', methods=['DELETE'])
def delete_data(id):
    data.pop(id)
    return jsonify({'message': 'Data deleted successfully'})

if __name__ == '__main__':
    app.run(debug=True)

Note that the endpoint is hosted at http://localhost:5000/api, where localhost refers to the local machine and 5000 is the default port used by Flask. If you want to change the endpoint URL or the response message, you can modify the code accordingly.

GET request to retrieve all data:

curl -X GET http://localhost:5000/api

POST request to add new data:

curl -d '{"4": "Peter"}' -H "Content-Type: application/json" -X POST http://localhost:5000/api

PUT request to update existing data with ID 2:

curl -d '{"name": "Maria"}' -H "Content-Type: application/json" -X PUT http://localhost:5000/api/2

DELETE request to delete existing data with ID 3:

curl -X DELETE http://localhost:5000/api/3

I hope this helps you understand how APIs work and how to use the main HTTP methods in your API endpoints!

Here are some Python requests examples for the API calls:

To make a GET request to retrieve all data:

import requests

response = requests.get('http://localhost:5000/api')

if response.ok:
    data = response.json()
    print(data)
else:
    print('Failed to retrieve data:', response.text)

To make a POST request to add new data:

import requests

new_data = {'4': 'Peter'}
headers = {'Content-Type': 'application/json'}
response = requests.post('http://localhost:5000/api', json=new_data, headers=headers)

if response.ok:
    data = response.json()
    print('Data added successfully:', data)
else:
    print('Failed to add data:', response.text)

To make a PUT request to update existing data with ID 2:

import requests

updated_data = {'name': 'Maria'}
headers = {'Content-Type': 'application/json'}
response = requests.put('http://localhost:5000/api/2', json=updated_data, headers=headers)

if response.ok:
    data = response.json()
    print('Data updated successfully:', data)
else:
    print('Failed to update data:', response.text)

To make a DELETE request to delete existing data with ID 3:

import requests

response = requests.delete('http://localhost:5000/api/3')

if response.ok:
    print('Data deleted successfully')
else:
    print('Failed to delete data:', response.text)

Note that in each case, we use the requests library to make the HTTP request to the API endpoint, and then check the response status code and content to determine if the request was successful or not.

So let us perform a real API call. In this case, we are going to add another item to the data set.

import requests

new_data = {'4': 'Peter'}
headers = {'Content-Type': 'application/json'}
response = requests.post('http://localhost:5000/api', json=new_data, headers=headers)

if response.ok:
    data = response.json()
    print('Data added successfully:', data)
else:
    print('Failed to add data:', response.text)
Data added successfully: {'4': 'Peter'}

Now that we have added the data added, let us check if this newly created item is committed.

import requests

response = requests.get('http://localhost:5000/api')

if response.ok:
    data = response.json()
    print(data)
else:
    print('Failed to retrieve data:', response.text)
{'1': 'John', '2': 'Mary', '3': 'Tom', '4': 'Peter'}

Now let us go ahead to delete an item;

import requests

response = requests.delete('http://localhost:5000/api/3')

if response.ok:
    print('Data deleted successfully')
else:
    print('Failed to delete data:', response.text)

Data deleted successfully
{'1': 'John', '2': 'Mary', '4': 'Peter'}

Follow below for a good resource on the subject;
https://towardsdatascience.com/the-right-way-to-build-an-api-with-python-cd08ab285f8f
https://auth0.com/blog/developing-restful-apis-with-python-and-flask/
https://anderfernandez.com/en/blog/how-to-create-api-python/

]]>