DEV Community

Cover image for Lesson 10 – Using Public APIs to Simulate Employee Data
Daniel Azevedo
Daniel Azevedo

Posted on

Lesson 10 – Using Public APIs to Simulate Employee Data

In this lesson, we’re going to use an actual public API to demonstrate how to interact with external services in Python. We’ll use the ReqRes API, which simulates user data. Although the API doesn’t represent real employee data, it’s useful for testing and practicing API integration with your HR systems.

We’ll cover:

  1. Sending requests to the ReqRes API to fetch employee-like data.
  2. Displaying the data in a Python application.
  3. Posting new employee-like data to the API.
  4. Error handling while making API calls.

1. Understanding the ReqRes API

The ReqRes API is designed for testing HTTP requests. It offers various endpoints to perform common actions like fetching user data, creating new users, and updating existing ones. This is a great tool to simulate how an HR system would interact with a third-party service to fetch or send employee data.

API Endpoints We’ll Use:

  • GET /api/users?page=2: Fetches a list of users (like employees).
  • POST /api/users: Simulates creating a new user (employee).

2. Fetching User Data (Simulated Employees) from the ReqRes API

Let’s start by fetching a list of users from the API. In a real-world scenario, this would be akin to fetching employee data from a payroll system or HR database.

First, make sure you have the requests library installed:

pip install requests
Enter fullscreen mode Exit fullscreen mode

Now, we’ll send a GET request to retrieve employee-like data.

Example: Fetching Employee Data

import requests

# URL to fetch employee-like data (simulated by ReqRes API)
url = "https://reqres.in/api/users?page=2"

# Sending a GET request to the API
response = requests.get(url)

# Check if the request was successful
if response.status_code == 200:
    # Parse the JSON data
    data = response.json()
    employees = data['data']

    # Display the employee-like data
    print("Employee List:")
    for employee in employees:
        print(f"ID: {employee['id']}, Name: {employee['first_name']} {employee['last_name']}, Email: {employee['email']}")
else:
    print(f"Failed to fetch data. Status code: {response.status_code}")
Enter fullscreen mode Exit fullscreen mode

What’s Happening Here:

  • We’re making a GET request to the ReqRes API to fetch a list of users (simulated employees).
  • If the request is successful, we parse the JSON response and display the user data, treating them as employees.

The output will look like this:

Employee List:
ID: 7, Name: Michael Lawson, Email: michael.lawson@reqres.in
ID: 8, Name: Lindsay Ferguson, Email: lindsay.ferguson@reqres.in
ID: 9, Name: Tobias Funke, Email: tobias.funke@reqres.in
Enter fullscreen mode Exit fullscreen mode

This simulates fetching employee data from an external system.


3. Posting New Employee Data to the ReqRes API

Let’s simulate adding a new employee to the system. In a real-world scenario, you’d send new employee data to a payroll or HR system.

Example: Adding New Employee Data

We’ll send a POST request to the ReqRes API to simulate adding a new employee.

# Employee data to send
new_employee = {
    "name": "John Doe",
    "job": "HR Manager"
}

# URL to post new employee-like data (simulated by ReqRes API)
url = "https://reqres.in/api/users"

# Sending a POST request to the API
response = requests.post(url, json=new_employee)

# Check if the request was successful
if response.status_code == 201:
    # Parse and display the created employee's data
    created_employee = response.json()
    print(f"New employee created: {created_employee['name']} with job: {created_employee['job']}")
else:
    print(f"Failed to create employee. Status code: {response.status_code}")
Enter fullscreen mode Exit fullscreen mode

What’s Happening Here:

  • We’re sending a POST request with the new employee’s data (name and job) to the ReqRes API.
  • If the request is successful, the API responds with the created employee’s data.

This simulates sending new employee information to an external HR system.

Output:

New employee created: John Doe with job: HR Manager
Enter fullscreen mode Exit fullscreen mode

4. Error Handling When Using APIs

When working with APIs, error handling is crucial. Network requests can fail due to issues like network connectivity, incorrect data, or server-side problems.

Example: Handling Errors in API Requests

Here’s how you can handle errors gracefully:

import requests

# URL to fetch employee-like data
url = "https://reqres.in/api/users?page=2"

try:
    # Sending a GET request
    response = requests.get(url)

    # Check if the request was successful
    response.raise_for_status()  # Raises HTTPError for bad responses

    # Parse the JSON data
    data = response.json()
    employees = data['data']

    # Display the employee-like data
    print("Employee List:")
    for employee in employees:
        print(f"ID: {employee['id']}, Name: {employee['first_name']} {employee['last_name']}, Email: {employee['email']}")
except requests.exceptions.HTTPError as http_err:
    print(f"HTTP error occurred: {http_err}")
except Exception as err:
    print(f"An error occurred: {err}")
Enter fullscreen mode Exit fullscreen mode

In this code:

  • We use response.raise_for_status() to catch HTTP errors (like 404 or 500).
  • A generic Exception is used to catch any other errors that might occur during the request.

5. Best Practices for Working with Public APIs

  1. Rate Limits: Many public APIs, including ReqRes, impose rate limits. This means you can only send a limited number of requests within a certain timeframe. Be mindful of this when testing.
  2. Authentication: For real-world APIs, you’ll often need to authenticate with an API key or OAuth token. Always keep your credentials secure.
  3. Data Validation: Ensure that the data you send to an API is properly validated. For example, check for required fields and correct data types before making a request.
  4. Timeouts and Retries: Network requests can sometimes be slow or fail. Use timeouts and retry logic to handle intermittent network issues.

Conclusion

In this lesson, you learned how to:

  • Use Python’s requests library to interact with a public API like ReqRes.
  • Fetch user data (simulated employees) from the API.
  • Post new employee data to the API.
  • Handle errors while making API requests.

This basic interaction with APIs is essential for building scalable and robust HR systems. APIs allow your application to communicate with external services, automating processes like fetching employee details, sending payroll information, and more.

Stay tuned, and keep coding!

Top comments (0)