<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Augustine Alul</title>
    <description>The latest articles on DEV Community by Augustine Alul (@21alul21).</description>
    <link>https://dev.to/21alul21</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1435874%2Ff8f193c3-0e6a-4355-9ce2-13367989f618.jpeg</url>
      <title>DEV Community: Augustine Alul</title>
      <link>https://dev.to/21alul21</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/21alul21"/>
    <language>en</language>
    <item>
      <title>Error Handling in Python: Best Practices. Explore how to handle exceptions effectively</title>
      <dc:creator>Augustine Alul</dc:creator>
      <pubDate>Sun, 12 Jan 2025 13:42:18 +0000</pubDate>
      <link>https://dev.to/21alul21/error-handling-in-python-best-practices-explore-how-to-handle-exceptions-effectively-3a21</link>
      <guid>https://dev.to/21alul21/error-handling-in-python-best-practices-explore-how-to-handle-exceptions-effectively-3a21</guid>
      <description>&lt;p&gt;&lt;strong&gt;Excerpt&lt;/strong&gt;:&lt;br&gt;
Errors are non-recoverable; when our program meets an error it quits or crashes instantly.&lt;/p&gt;

&lt;p&gt;A good programmer ensures that their code or piece of software is written to gracefully handle errors/exceptions that may arise from the usage of the software without crashing or producing bad results. Imagine writing software for a financial institution that accepts numbers only from the user and an alphabet was entered instead of a number for arithmetic operation, this would typically raise an error, and the software would crash just because of one user if there is no proper mechanism to handle the error. This is not a good thing at all—it is bad for business, can lead to customers feeling frustrated and someone might end up losing their job for incompetence.&lt;/p&gt;

&lt;p&gt;In this article, we’ll learn how to handle errors that may arise in our code due to user interaction in the best possible way. Stay tuned.&lt;/p&gt;
&lt;h2&gt;
  
  
  Prerequisites
&lt;/h2&gt;

&lt;p&gt;This article is suitable for:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Python software developers seeking to learn how to handle exceptions in their code.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Persons already conversant with Python who wish to learn about the concept of error handling in Python.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Existing professionals who seek to sharpen existing knowledge on error handling in Python.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;
  
  
  Objectives
&lt;/h2&gt;

&lt;p&gt;By going through this article, the reader should be able to:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Clearly understood the concept of error handling in Python and why it is important.&lt;/li&gt;
&lt;li&gt;Learn about custom exception classes and how to implement them.&lt;/li&gt;
&lt;li&gt;Understand the key differences between errors and exceptions in Python.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;
  
  
  Explaining Errors and Exceptions
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Errors&lt;/em&gt;&lt;/strong&gt; and &lt;strong&gt;&lt;em&gt;exceptions&lt;/em&gt;&lt;/strong&gt; are oftentimes used interchangeably, but they technically mean different things. In Python both &lt;strong&gt;&lt;em&gt;errors&lt;/em&gt;&lt;/strong&gt; and &lt;strong&gt;&lt;em&gt;exceptions&lt;/em&gt;&lt;/strong&gt; are subclasses of &lt;strong&gt;&lt;em&gt;BaseException&lt;/em&gt;&lt;/strong&gt;, this further shows that they have similarities in common even though they are different.&lt;/p&gt;
&lt;h2&gt;
  
  
  Errors
&lt;/h2&gt;

&lt;p&gt;Errors are non-recoverable; when our program meets an error it quits or crashes instantly. There is no room for handling errors programmatically even if you might expect them. Some of the errors are listed below:&lt;/p&gt;
&lt;h3&gt;
  
  
  SyntaxError:
&lt;/h3&gt;

&lt;p&gt;This is one of the most common types of errors programmers face, it results when a code is not following the correct Python syntax and can be detected during parsing. It Is easily an issue for learners of people switching from another programming language to Python.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;name = “Austin”;
print(name)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This results in a SyntaxError because, in Python, statements do not end with a semicolon.&lt;/p&gt;

&lt;h3&gt;
  
  
  IndentationError:
&lt;/h3&gt;

&lt;p&gt;This error occurs when Python code is not properly indented and is detected when the code is being parsed. Indentation in Python is very important. It is the only way code can be defined in blocks in Python, unlike most languages where curly braces are used.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;active = True
if (active):
print(“The user is active”)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This code will result in an error be my cause of improper indentation. It should be:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if (active):
    print(“The user is active”)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Exceptions
&lt;/h2&gt;

&lt;p&gt;Exceptions in Python occur at runtime. Unlike Errors, they can be handled or caught properly programmatically for our program to continue running without crashing. In other words, they are recoverable. Here are some of the common exceptions found in Python:&lt;/p&gt;

&lt;h2&gt;
  
  
  Built-in Exceptions
&lt;/h2&gt;

&lt;p&gt;These types of exceptions are part of the Python programming language. Listed below are a few of them:&lt;/p&gt;

&lt;h3&gt;
  
  
  ValueError:
&lt;/h3&gt;

&lt;p&gt;This occurs when an invalid parameter is given to a function even though the type may be correct.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
def str_num(num_string):
    return(int(string))

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;From the code snippet above, if we pass in a numeric string to the function, it will be successfully converted to a number, otherwise, it will yield a ValueError.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
print(str_num(“123”)) #works perfectly
print(str_num(“abc”)) #raises a ValueError 

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  TypeError:
&lt;/h3&gt;

&lt;p&gt;This is raised when the argument(s) of inappropriate type is passed to the function.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def addition(num1, num2):
    return num1 + num2
# calling the function
addition(5, A)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This raises a TypeError.&lt;/p&gt;

&lt;h3&gt;
  
  
  IndexError:
&lt;/h3&gt;

&lt;p&gt;This arises when you are trying to access a value in a list with a wrong index.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;my_list = [“dog”, “cat”]
my_list[2]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This results in an IndexError because my_list[2] is not accessible.&lt;/p&gt;

&lt;h3&gt;
  
  
  KeyError:
&lt;/h3&gt;

&lt;p&gt;This is raised when trying to access a value in a dictionary using the wrong or inexistent key.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;my_dict = {“name”: “Austin”, “occupation”: “Software Engineer”}
my_dict[“age”]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This raises a KeyError.&lt;br&gt;
You can find other built-in exceptions &lt;a href="https://docs.python.org/3/library/exceptions.html#bltin-exceptions" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;h2&gt;
  
  
  Custom Exceptions
&lt;/h2&gt;

&lt;p&gt;Custom exceptions are defined by the programmer. Here, Python makes it possible to manually define conditions that a program should check for during execution and raise an exception if found. You can achieve this by creating a class that inherits from the Exception class.&lt;/p&gt;
&lt;h2&gt;
  
  
  Handling Exceptions
&lt;/h2&gt;

&lt;p&gt;Handling exceptions ensures that our software application has predictable performance when encountered by certain errors that arise during the application lifecycle. In this section, you will learn how this is done programmatically.&lt;/p&gt;
&lt;h3&gt;
  
  
  Using the try-except statements
&lt;/h3&gt;

&lt;p&gt;The try-except statements provide a safe way of handling codes that are likely going to raise an error or exception. The &lt;strong&gt;&lt;em&gt;try&lt;/em&gt;&lt;/strong&gt; statement wraps the problematic code or &lt;strong&gt;&lt;em&gt;try clause&lt;/em&gt;&lt;/strong&gt;; this is the part of the code that is mostly going to bring about an error to the entire program; this is likely to happen when receiving inputs from users, reading from files, to name a few. &lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;&lt;em&gt;except&lt;/em&gt;&lt;/strong&gt; statement marks the beginning of the &lt;strong&gt;&lt;em&gt;except clause&lt;/em&gt;&lt;/strong&gt;; Which is the remaining code wrapped in the except block. The &lt;strong&gt;&lt;em&gt;except clause&lt;/em&gt;&lt;/strong&gt; handles the exception raised in the &lt;strong&gt;&lt;em&gt;try block&lt;/em&gt;&lt;/strong&gt;. &lt;/p&gt;

&lt;p&gt;Let me walk you through the execution workflow. Your Python program typically executes until it reaches the try block where your “problematic” code is likely going to be, if there is no possible error while executing the code in the try block at the time, it skips the except block and continues to execute the rest part of the codebase. But if an error is encountered while executing the code in the try block, an exception object is created after which the control jumps immediately to the except block where it should be handled by the matching exception class.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;try:
    age = int(input(“enter your age”))
    print(f“you were born {age} years ago”)

except ValueError:
    print(“ValueError was raised, please enter numbers only”)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;From the code snippet above, if a non-numeric value is passed to the program, an exception object is created and a ValueError is raised. The control immediately jumps to the except block where it scans for the appropriate exception class. Here, the ValueError class is sufficient. The error is handled properly. But if the proper class is not found, the control moves to the outer try block if there is any, if the exception is not properly handled still, the program crashes.&lt;/p&gt;

&lt;h3&gt;
  
  
  Using multiple exception classes with one except statement
&lt;/h3&gt;

&lt;p&gt;Multiple exception classes can be checked for and the specific exception handled. This approach is preferred if you are not sure which exception out of a few, will result from the execution of your code. See the code snippet below.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;except (RuntimeError, TypeError, NameError):
    pass

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Wildcard Exception class
&lt;/h3&gt;

&lt;p&gt;The Exception class is a direct subclass of the BaseException. The Exception class is the base class of all the non-fatal exceptions. &lt;br&gt;
Most of the time, the Exception class is sufficient for handling most of the exceptions raised during code execution.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;try:
    # Code that may raise an exception
except Exception:
    # Handle the exception

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Even though the Exception class is capable of handling on-fatal exceptions, it is best to use it sparingly. Use the right Exception class, as it is more beneficial for debugging and making your code readable.&lt;/p&gt;

&lt;h2&gt;
  
  
  Using the finally statement
&lt;/h2&gt;

&lt;p&gt;The piece of code wrapped inside the finally block executes whether or not an exception occurs. This makes it suitable for handling clean-up tasks; closing files, and releasing memory resources.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
try:
    # Code that might raise an exception
except SomeException:
    # Handle the exception
else:
    # Optional: Executes if no exceptions occur
finally:
    # Code that always executes, no matter what

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Creating custom exception classes
&lt;/h2&gt;

&lt;p&gt;Creating custom exceptions gives the programmer the ability to come up with specific exceptions for a software program. These can entail special conditions or edge cases that could be detrimental to the functioning of the particular software program in question. The custom exception classes defined must inherit from the Exception class.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class InvalidAgeError(Exception):
    pass

def check_age(age):
    if age &amp;lt; 0:
        raise InvalidAgeError("Age cannot be negative.")

try:
    check_age(-5)
except InvalidAgeError as e:
    print(f"Error: {e}")

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The code snippet above shows how custom exceptions are created and used. It can be used in a more complex way, depending on the use case.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why error/exception handling is important
&lt;/h2&gt;

&lt;p&gt;“Don't trust the user” is a common saying amongst software developers, this reiterates that you cannot fully determine how the users will interact with your software application; what type of inputs they pass in, and some other edge cases that you as a programmer might not have thought of while writing the application. Explained below are some of the reasons why it is important to handle errors/exceptions properly:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Prevents Crashes
Without exception handling, an unhandled error can cause your program to crash abruptly. This can lead to data loss or a poor user experience.
Example:
Without Exception Handling:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;print(10 / 0)  # ZeroDivisionError: division by zero

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With Exception Handling:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;try:
    print(10 / 0)
except ZeroDivisionError:
    print("Cannot divide by zero!")

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Improves User Experience
Properly handled exceptions provide meaningful error messages instead of cryptic system errors, keeping the application user-friendly.
Example:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;try:
    age = int(input("Enter your age: "))
except ValueError:
    print("Invalid input! Please enter a number.")

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Maintains Application Stability
It allows the application to continue running even after encountering an error, ensuring stability.
Example:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def divide(a, b):
    try:
        return a / b
    except ZeroDivisionError:
        return "Division by zero is not allowed!"

print(divide(10, 2))  # Output: 5.0
print(divide(10, 0))  # Output: Division by zero is not allowed!

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Handles Edge Cases
Exception handling lets you account for unpredictable scenarios, such as network failures, missing files, or invalid user input.
Example:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;try:
    with open("data.txt", "r") as file:
        content = file.read()
except FileNotFoundError:
    print("The file was not found.")

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Encourages Clean Code&lt;br&gt;
By separating normal logic from error-handling logic, exception handling makes your code easier to read, debug, and maintain.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Facilitates Debugging&lt;br&gt;
With detailed error messages and exception logging, developers can quickly identify and fix issues in the code.&lt;br&gt;
Example:&lt;br&gt;
&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import logging

try:
    result = 10 / 0
except Exception as e:
    logging.error("An error occurred", exc_info=True)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Essential for Critical Systems
In systems where reliability is vital (e.g., banking, healthcare), exception handling is necessary to ensure errors are managed safely without data corruption or loss.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Errors and exceptions are most times used interchangeably in programming speak. The key difference between errors and exceptions in Python is in how they affect our software programs. Errors like syntax errors, and indentation errors crash our program when it is being parsed by the interpreter. Exceptions on the other hand crash our programs during runtime if not handled properly. Custom exceptions extend error-handling capabilities by making it possible for the programmer to define exception classes that are peculiar to a particular software application.&lt;/p&gt;

&lt;p&gt;Error handling is also very important for debugging. It makes it possible to see why errors are occurring in our application, arming the software maintainer with enough information to fix the problem. Always ensure to introduce exception handling in your code appropriately to ensure a robust software application.&lt;/p&gt;

&lt;p&gt;Thanks for reading.&lt;/p&gt;

</description>
      <category>productivity</category>
      <category>python</category>
      <category>exception</category>
    </item>
    <item>
      <title>Working with APIs in Python: A Practical Guide</title>
      <dc:creator>Augustine Alul</dc:creator>
      <pubDate>Sun, 29 Dec 2024 12:33:53 +0000</pubDate>
      <link>https://dev.to/21alul21/working-with-apis-in-python-a-practical-guide-3cok</link>
      <guid>https://dev.to/21alul21/working-with-apis-in-python-a-practical-guide-3cok</guid>
      <description>&lt;p&gt;Excerpt:&lt;br&gt;
“APIs make software applications modular. They speed up software development time”.&lt;/p&gt;

&lt;p&gt;Application Programming Interface (or API) is an abstracted layer that enables communication between different software applications and components. How does this communication happen? Web APIs which happens to be what we will be dwelling on in this article, sit between a piece of software application being used by a client and the database where the information is stored. Read about the different types of APIs &lt;a href="https://www.ibm.com/think/topics/api" rel="noopener noreferrer"&gt;here&lt;/a&gt;. The communication happens irrespective of the programming language in which the individual software applications are written; whether Python, Java, JavaScript etc. Provided the request sent from the software applications to the API is valid, be it a retrieval, update, delete, or create operation.&lt;/p&gt;

&lt;p&gt;Imagine a social media platform like Instagram where a particular user posts a picture, what happens internally is that the user is making a POST request to the prescribed Instagram API endpoint; sending a picture to the database. Another user gets to see the post by making a GET request to the API without even knowing so when scrolling on the timeline. You see that there is communication there—through the API.&lt;/p&gt;

&lt;p&gt;This can also be the case even when the two users are communicating through the API with software applications written in different languages.&lt;br&gt;
The illustration below shows two distinct software applications communicating through an API.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fb1n79lm5bxxvgyvir8v3.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fb1n79lm5bxxvgyvir8v3.jpeg" alt="Image showing two softwares communicating through an API" width="800" height="1076"&gt;&lt;/a&gt;&lt;br&gt;
Photo by author&lt;/p&gt;

&lt;p&gt;Furthermore—APIs make software applications modular. They speed up software development time. Modular in the sense that the API implementation is separated from our code base, we just have to make calls to the API. It speeds up development time because we don’t have to write code that provides functionality similar to the one the API does from scratch, we just have to invoke it.&lt;/p&gt;

&lt;p&gt;In this article, you will learn how to utilize a publicly available API using Python. Stay tuned. &lt;/p&gt;
&lt;h2&gt;
  
  
  Prerequisites
&lt;/h2&gt;

&lt;p&gt;This article is suitable for beginner-level Python programmers seeking to broaden their understanding of APIs with specific implementation in Python. &lt;br&gt;
To practice alongside, ensure that your machine is connected to the internet.&lt;/p&gt;

&lt;p&gt;This article also serves as a refresher for more experienced Python developers.&lt;/p&gt;
&lt;h2&gt;
  
  
  Objectives
&lt;/h2&gt;

&lt;p&gt;By going through to the end of this article, you should:&lt;br&gt;
Learn about the requests library in Python.&lt;br&gt;
Know how to make GET, PUT, PATCH, DELETE and POST requests.&lt;br&gt;
Learn to store and utilise the data received from an API call inside your code.&lt;/p&gt;
&lt;h2&gt;
  
  
  Understanding the requests library
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;requests&lt;/em&gt;&lt;/strong&gt; is one of the most downloaded Python packages with around 30M downloads every week according to &lt;a href="https://pypi.org/project/requests/" rel="noopener noreferrer"&gt;pypi&lt;/a&gt;. It enables you to send HTTP requests easily in Python. requests is a tested and trusted Python package, used by many established brands like IBM. Find the source code &lt;a href="https://github.com/psf/requests" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;br&gt;
Some of the “beloved” features of requests are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Keep-Alive &amp;amp; Connection Pooling&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;International Domains and URLs&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Sessions with Cookie Persistence&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Browser-style SSL Verification&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Automatic Content Decoding&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Basic/Digest Authentication&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Elegant Key/Value Cookies&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Automatic Decompression&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Unicode Response Bodies&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;HTTP(S) Proxy Support&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Multipart File Uploads&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Streaming Downloads&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Connection Timeouts&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Chunked Requests&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;.netrc Support&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;
  
  
  Getting started with requests
&lt;/h2&gt;

&lt;p&gt;I assume you already have Python installed on your machine. Install the requests package by following the instructions below:&lt;br&gt;
On Linux or Mac OS open your terminal and do:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;python3 -m pip install requests
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;On Windows do:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;python -m pip install requests
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This downloads the &lt;strong&gt;&lt;em&gt;requests&lt;/em&gt;&lt;/strong&gt; package to your machine.&lt;/p&gt;

&lt;h3&gt;
  
  
  Making a GET request
&lt;/h3&gt;

&lt;p&gt;A GET request is made to retrieve existing data. It returns an object that can be further explored to get more details about the request made by calling the desired attribute on it. See the example usage below:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Create a Python file, for example, &lt;strong&gt;&lt;em&gt;get_request.py&lt;/em&gt;&lt;/strong&gt;, in the file, write the following code:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Import the requests module
import requests

# Making a simple GET request
response_object = requests.get("https://jsonplaceholder.typicode.com/posts")

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;From the response_object, different attributes can be called:&lt;br&gt;
status_code: HTTP status code of the response.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;.text: The response body as a string.&lt;/li&gt;
&lt;li&gt;.json(): Parses the response body as JSON (if applicable).&lt;/li&gt;
&lt;li&gt;.content: The response body as raw bytes.&lt;/li&gt;
&lt;li&gt;.headers: A dictionary of the response headers.&lt;/li&gt;
&lt;li&gt;.cookies: Cookies set by the server.&lt;/li&gt;
&lt;li&gt;.url: The final URL after redirects.&lt;/li&gt;
&lt;li&gt;.elapsed
In this article, we will focus more on the .json() attribute.
In your requests.py file, call the &lt;strong&gt;&lt;em&gt;.json()&lt;/em&gt;&lt;/strong&gt; attribute on the response_object
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;json_data = response_object.json()
print(json_data)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;The JSON returned is stored in the json_data variable, and can be used inside your program.&lt;br&gt;
The following will be outputted to your console.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqakbliwm7peuah3me9kt.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqakbliwm7peuah3me9kt.png" alt="Image showing a 201 status code" width="624" height="158"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h3&gt;
  
  
  Making a POST request
&lt;/h3&gt;

&lt;p&gt;POST request sends data to a specified endpoint, creating a new record. Unlike the GET method which seeks to retrieve already existing data. Follow the steps below to make a post request:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Create a new file named &lt;strong&gt;&lt;em&gt;post_request.py&lt;/em&gt;&lt;/strong&gt; or whichever name that is convenient. Write the following code in the file:
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Import the requests module
import requests


# Making a simple POST request


data = {'userId': 1, 'id': 1, 'title': 'This is for POST request', \
        'body': 'This body is modified for this technical writing article by Augustine Alul'}
response_object = requests.post("https://jsonplaceholder.typicode.com/posts/", data=data)


print(response_object.status_code)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;This sends data to the prescribed endpoint and also returns a response object; this object possesses several beneficial information about the POST request sent. It can be accessed by calling the suitable attribute on the object.&lt;br&gt;
Call the &lt;strong&gt;&lt;em&gt;status_code&lt;/em&gt;&lt;/strong&gt; attribute on the response object to be sure that the operation was successful. Update your code.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;print(response_object.status_code)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It returns a 201, which indicates that your POST request was successful and a new resource has been created. As shown in the image below.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Focuah8mtzgndacg9ixuj.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Focuah8mtzgndacg9ixuj.png" alt="Image showing a 201 status code" width="800" height="25"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Making a PUT request
&lt;/h3&gt;

&lt;p&gt;PUT request involves replacing existing records with new ones; it takes new data from the sender or client and replaces the existing data with it.&lt;br&gt;
This is how you make a PUT request:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Create a new Python file, for this article, we are using put_request.py. Write the following code in it.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Import the requests module
import requests

# Making a simple PUT request


data = {'userId': 1, 'id': 1, 'title': 'This is for PUT', \
        'body': 'This body is modified for this technical writing article by Augustine Alul'}
response_object = requests.put("https://jsonplaceholder.typicode.com/posts/1", data=data)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Making a DELETE request
&lt;/h3&gt;

&lt;p&gt;This ensures the removal of a certain record or data. The record to be removed is always specified through its unique ID, which is usually specified.&lt;br&gt;
This is how you perform a DELETE operation:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Create a new Python file, for this article, we are using &lt;em&gt;&lt;strong&gt;delete_request.py&lt;/strong&gt;&lt;/em&gt;. Write the following code in it:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Making a simple DELETE request
response_object = requests.delete("https://jsonplaceholder.typicode.com/posts/1")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Making a PATCH request
&lt;/h3&gt;

&lt;p&gt;Use the PATCH method whenever you want to make partial changes to already existing records or data.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Create a new Python file, for this article, we use patch_request.py. Write the following code in it:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Import the requests module
import requests

# Making a simple PATCH request

data = {'userId': 1, 'id': 1, 'title': 'This is for PATCH', \
        'body': 'This body is modified for this technical writing article by Augustine Alul'}
response_object = requests.patch("https://jsonplaceholder.typicode.com/posts/1", data=data)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;The &lt;em&gt;&lt;strong&gt;requests&lt;/strong&gt;&lt;/em&gt; library provides a simplistic way of making HTTP requests in your Python code; it enables easy interaction with APIs and returns an object that provides useful information about the request made, by simply calling the desired attribute (the attributes can be found in the article).&lt;br&gt;
Working with APIs in Python never got any easier—there are other popular libraries for interacting with APIs in Python, but the requests library was chosen for its simplicity.&lt;br&gt;
Thanks for sticking around to the end of this article, this gives you a good background to start working with APIs in Python.&lt;/p&gt;

</description>
      <category>python</category>
      <category>api</category>
      <category>programming</category>
    </item>
    <item>
      <title>Understanding decorators in Python</title>
      <dc:creator>Augustine Alul</dc:creator>
      <pubDate>Sun, 08 Sep 2024 20:50:48 +0000</pubDate>
      <link>https://dev.to/21alul21/understanding-decorators-in-python-2fol</link>
      <guid>https://dev.to/21alul21/understanding-decorators-in-python-2fol</guid>
      <description>&lt;p&gt;&lt;strong&gt;Introduction:&lt;/strong&gt;&lt;br&gt;
Have you ever come across a Python code base where "@login_required" or where the "@" sign is used with any other suffix on top of a function or class and you immediately begin to wonder what it is or what is its purpose? &lt;/p&gt;

&lt;p&gt;Or have you in the past used a framework where the documentation says you should use a certain decorator to achieve a particular functionality but you just do not know how the implementation is done under the hood and would love to find out? &lt;/p&gt;

&lt;p&gt;Or maybe, it is understandable that you are new to the concept of decorators and would love to learn about it, hang in there, you are well on track to do so.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Prerequisites:&lt;/strong&gt;&lt;br&gt;
For maximum understanding of the concepts in this tutorial, it is necessary to have a background knowledge of Python programming.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What are decorators:&lt;/strong&gt;&lt;br&gt;
Decorators are used in Python to give extra functionality to classes, and functions without altering the initial code structure of the class or function as the case may be. Decorators are sometimes referred to as "syntactic sugar", as they tend to improve the behavior of a class or function.&lt;/p&gt;

&lt;p&gt;If you are caught up in a situation whereby you have a function of class bundled up with certain functionalities that are already in use by a larger part of your program or software, as the case may be, and you want the class/function to have a slight modification for an intended use within the program, and at the same time you don't want to break the functioning of the existing codebase because of how tightly coupled it is, what do you think is the best approach in this situation?&lt;br&gt;
You guessed right, all you simply need to do is decorate the class/function to achieve the desired functionality without breaking the existing program where they are being used.&lt;br&gt;
Just like it was stated in the introductory part of this tutorial where "@login_required" was used to cite an instance, it is indeed a decorator used in the Flask framework, which happens to be a popular backend framework, whenever the "@login_required" decorator is placed on top of a view function, it causes access to the view function to be restricted to just the users that have been authenticated/logged in to the application. Here again, we see the real-world application of decorators and how it can be utilized in building software.&lt;/p&gt;

&lt;p&gt;From a technical perspective and a lower level, decorators are functions that take other functions or classes as arguments and then wrap them in a wrapper function that extends/modifies their functionality, then the decorator function now returns the outcome of the modification done by the wrapper function.&lt;/p&gt;

&lt;p&gt;Here are some code snippets for aid clarification and better understanding;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def hello():
    print("Hello readers")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;hello() is a function that has been defined to display "Hello readers" whenever it is being called, and it might already be in use in a larger part of my program.&lt;/p&gt;

&lt;p&gt;And now I need to modify the display message from the hello function without defining a new function explicitly in my program, I can apply decoration on the hello() function to achieve the desired modified outcome by simply using a decorator.&lt;/p&gt;

&lt;p&gt;The first step is to define your decorator function&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; def decorator(func):
    def wrapper():
        print("in the decorated function")
        func()
        print("bye, leaving the decorated function")
    return wrapper
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The second step and last step is to place the decorator function as a suffix to the "@" sign on top of the function to be decorated.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@decorator
def hello():
    print("Hello readers")

# Calling the decorated function
hello()

This outputs:

        in the decorated function
        Hello readers
        bye, leaving the decorated  function
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In summary, decorators in python modify the behavior of functions and classes without altering the structure of the already defined code, thereby improving certain behaviors of the class or function.&lt;/p&gt;

&lt;p&gt;Thanks for reading.&lt;/p&gt;

&lt;p&gt;Happy coding...&lt;/p&gt;

</description>
      <category>python</category>
      <category>programming</category>
      <category>decorators</category>
      <category>web</category>
    </item>
    <item>
      <title>Queue and Stack Essentials: A Python Programmer's Guide</title>
      <dc:creator>Augustine Alul</dc:creator>
      <pubDate>Fri, 26 Apr 2024 20:53:16 +0000</pubDate>
      <link>https://dev.to/21alul21/queue-and-stack-essentials-a-python-programmers-guide-4ji5</link>
      <guid>https://dev.to/21alul21/queue-and-stack-essentials-a-python-programmers-guide-4ji5</guid>
      <description>&lt;p&gt;&lt;strong&gt;Introduction&lt;/strong&gt;&lt;br&gt;
Data structures in programming can be seen as a way of storing and organizing data to ensure that the data stored therein can be efficiently utilized in a program, thereby improving the functionality of the software it was applied.&lt;br&gt;
Most data structures are language agnostic; in that, they can be implemented using any programming language of choice. Although some programming languages have their specific in-built data structures, still, the concept of data structures remains the same regardless; which is to store and organize data for programming applications. &lt;/p&gt;

&lt;p&gt;In this article, we will explore queue and stack data structures using Python. For optimum understanding, it is requisite that you know basic programming preferably in Python programming language.&lt;/p&gt;

&lt;p&gt;Queue and stack are an example of linear data structures, and by that, I mean that each constituent element is sequentially linked to another. Think of a chain, for instance, each link is connected to the next one.&lt;br&gt;
Data stored in a linear data structure can be accessed one after another while traversing. Let’s delve into queue and stack individually for more clarity.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Queue Data Structure&lt;/strong&gt;&lt;br&gt;
Queues operate on the 'First-in-First-out' principle(FIFO), what this means is that retrieval and insertion of data in a queue data structure occur at the beginning and end respectively and the right term for this operation is dequeuing and enqueueing. In a real-world scenario, a queue can be likened a a system whereby people are lined up in a McDonald’s outlet to get pizza, and they are attended to according to the time they came, the persons who came earlier are always in the front of the the queue while those who came later queue behind them. Dequeuing happens at the front when someone takes his/her turn and eventually buys the pizza and leaves, enqueueing occurs at the end when a new person joins the queue. &lt;br&gt;
The Python implementation of a queue is demonstrated in the code snippet below.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#creating an object of the dequeue class
my_queue = dequeue(['first_person', 'second_person', 'third_person', 'fourth_person'])

#enqueueing 

my_queue.append('fifth_person')
print(my_queue) # outputs ['first_person', 'second_person', 'third_person', 'fourth_person', 'fifth_person']

#dequeueing 
my_queue.leftpop()
print(my_queue)
# outputs ['second_person', 'third_person', 'fourth_person', 'fifth_person'] 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;From the code snippet above, we have been able to demonstrate the enqueueing and dequeueing operations of a queue data structure.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Stack Data Structure&lt;/strong&gt;&lt;br&gt;
Stack data structure follows the 'Last-in-First-out'(LIFO) principle, retrieving and addition of data occurs at the top of the stack, this implies that the last element that is added to the stack is the first element to be retrieved/removed.&lt;br&gt;
In a real-life scenario, a stack can be likened to a pile of dishes to be washed, the first plate in the pile of dishes is positioned at the bottom and the last dish added is at the top of the stack, this simply implies that if we are to start picking out the dishes for washing, we naturally start picking from the top which happens to be the last dish added to the stack of dishes, hence we are unknowingly following the LIFO approach.&lt;br&gt;
Below is a code snippet to demonstrate stack operation using Python.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#creating a stack object
dish_stack = dequeue(['first_dish', 'second_dish', 'third_dish'])

#adding data to the stack
dish_stack.append('fourth_dish')
print(dish_stack) #outputs ['first_dish', 'second_dish', 'third_dish', 'fourth_dish']

#removing data from the stack
dish_stack.pop()
print(dish_stack) #outputs ['first_dish', 'second_dish', 'third_dish']
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To reiterate, queue and stack are an example of linear data structures. The queue data structure operates on the FIFO principle meanwhile the stack operates on LIFO.&lt;br&gt;
Although the dequeue class has some other methods for manipulating queue and stack objects that were not included in this article, the methods used in this article are sufficient to ensure a basic understanding of how queue and stack data structures primarily behave.&lt;/p&gt;

&lt;p&gt;Thanks for reading.&lt;/p&gt;

</description>
      <category>python</category>
      <category>queue</category>
      <category>stack</category>
      <category>datastructures</category>
    </item>
  </channel>
</rss>
