Python – 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.2 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/

]]>
Using Python and pyFirmata to Control Arduino Boards on Ubuntu https://www.expertnetworkconsultant.com/python-programming-foundations-for-the-network-engineer/using-python-and-pyfirmata-to-control-arduino-boards-on-ubuntu/ Sat, 10 Oct 2020 05:00:18 +0000 http://www.expertnetworkconsultant.com/?p=4156 Continue readingUsing Python and pyFirmata to Control Arduino Boards on Ubuntu]]> Why am I Using Python and pyFirmata to Control Arduino Boards on Ubuntu?

So here is the deal, I had a great affinity for Arduino until I fell in love with Python. My life has never been the same again. Aaahhh, do I need to ditch my Ardunio control boards to use a Raspberry Pi instead? How about all the interesting projects I made back then in Arduino? Could I not learn to code them in Python and just use my Python scripts to control them?

Things you’ll need;

  • Personal Computer Linux | MAC | Windows with Arduino IDE.
  • Arduino Board (I have used the Elegoo Uno Version here)
  • USB cable for Arduino.
  • Breadboard
  • Jumper Wires
  • LED Light
  • Resistor

Step 1: Upload Standard Firmata on your Arduino board (Firmata is a serial communication protocol that can control the Arduino’s GPIO)
Files > Examples > Firmata > StandardFirmata (You will only need to upload this once).
Using Python and pyFirmata  to Control Arduino Boards on Ubuntu - Install Standard Firmata on Arduino

What is Firmata

Firmata is an intermediate protocol that connects an embedded system to a host computer, and the protocol channel uses a serial port by default. The Arduino platform is the standard reference implementation for Firmata. The Arduino IDE comes with the support for Firmata.

This could work perfectly with Odyssey-X86 with its onboard Arduino Core meaning that you can control the Arduino Core simply using Firmata protocol with different programming languages too!

The Firmata library implements the Firmata protocol for communicating with software on the host computer. This allows you to write custom firmware without having to create your own protocol and objects for the programming environment that you are using.

To use this library
#include <Firmata.h>

Step 2:
Install PyFirmata on Ubuntu

pip3 install pyfirmata

Using Python and pyFirmata  to Control Arduino Boards on Ubuntu - pip3 install pyfirmata


Step 3:

Build your circuit. Roll your sleeves and get your jumper wires, resistor and LED together in a very simple circuit like the one below;

Blinking LED Circuit

Schematic: How to wire up your circuit
simple led blink ardunio circuit

Step 4: Write Your Python Blink LED Program

from pyfirmata import Arduino
import time

if __name__ == '__main__':
    board = Arduino('/dev/ttyACM1')
    print("Communication Successfully Initiated ")

Arduino Uno on DEV TTY ACM1

    while True:
        board.digital[13].write(1)
        time.sleep(0.5)
        board.digital[13].write(0)
        time.sleep(0.5)

Full Code: Blink LED Python Program
blink led python code


from pyfirmata import Arduino, util
import time

if __name__ == '__main__':
board = Arduino('/dev/ttyACM1')
print("Communication Successfully Initiated")

while True:
board.digital[9].write(1)
time.sleep(0.5)
board.digital[9].write(0)
time.sleep(0.5)

Step 5 Hit Run and see it in action
Blinking LED Circuit in action

Troubleshooting
Your USB connection to your Arduino board is disconnected if you see this sudden error;

raise SerialException('write failed: {}'.format(e))
serial.serialutil.SerialException: write failed: [Errno 5] Input/output error

Here you are, a step by step guide to get Python to control your GPIOs on Arduino. Hope this little project helps you on your journey to great electronics?

See more python projects like this fading led light project.

]]>