Employees API

Below, you will find detailed information on how to use the Employees API. This API provides sample data of employees in an imaginary company for educational and testing purposes. No API key is required.

Base URL

The base URL for all endpoints is:

https://boringapi.com/api/v1

Employee Data Fields

Each employee record contains the following fields:

  • id: A unique identifier for the employee.
  • email: The employee's email address.
  • phone: The employee's phone number.
  • first_name: The employee's first name.
  • last_name: The employee's last name.
  • birth_date: The employee's date of birth.
  • department: The department where the employee works.
  • address: The employee's residential address.
  • gender: The employee's gender.
  • experience: The number of years the employee has worked.
  • is_married: Indicates if the employee is married (boolean).
  • created_at: The date and time when the employee record was created.
  • updated_at: The date and time when the employee record was last updated.

You can try this API online with your web browser here.

Endpoints

1. List All Employees

Method: GET

Endpoint:

/employees

Query Parameters:

  • search (optional): A string to search for employees by first name, last name, or email.
  • page (optional): An integer specifying the page number of employees to return. Default is 1.
  • limit (optional): An integer specifying the number of employees to return per page. Default is 10. Maximum is 100.
  • sort_by (optional): A string to specify the field to sort employees by. Can be one of id, first_name, last_name, email, salary, birth_date. Default is id.
  • sort_order (optional): A string to specify the order to sort employees by. Can be either asc or desc. Default is desc.

Responses:

  • 200 OK: Returns a list of employees.
  • 422 Unprocessable Entity: Validation error in the request parameters.

Example:

https://boringapi.com/api/v1/employees/?search=John&page=2&limit=5&sort_by=salary&sort_order=asc

2. Get a Single Employee

Method: GET

Retrieves details of a single employee by their ID:

/employees/{employee_id}

Path Parameters:

  • employee_id (required): The ID of the employee.

Responses:

  • 200 OK: Returns the details of the employee.
  • 422 Unprocessable Entity: Validation error in the request parameters.

Example Request:

https://boringapi.com/api/v1/employees/123

Result:

{
    "success": true,
    "message": "Employee with ID 123 found!",
    "employee": {
        "first_name": "Sean",
        "last_name": "Daugherty",
        "phone": "457-260-0713x5913",
        "birth_date": "1979-08-21T00:00:00",
        "salary": 17500,
        "department": "Sales",
        "created_at": "2024-05-19T07:51:11.028065",
        "email": "[email protected]",
        "id": 123,
        "address": "31105 Olivia Spur\nHensonfurt, MP 58681",
        "gender": "male",
        "experience": 25,
        "is_married": true,
        "updated_at": "2024-05-19T07:51:11.028065"
    }
}

3. Get Random Employees

Method: GET

Endpoint: 

/employees/random

Query Parameters:

  • num (optional): An integer specifying the number of random employees to return. Default is 1. Maximum is 10.

Responses:

  • 200 OK: Returns a list of random employees.
  • 422 Unprocessable Entity: Validation error in the request parameters.

Code Examples

JavaScript

Using fetch to interact with the API:

// Example: List all employees with parameters
async function listEmployees(search, page = 1, limit = 10, sortBy = 'id', sortOrder = 'desc') {
    const params = new URLSearchParams({ search, page, limit, sort_by: sortBy, sort_order: sortOrder });
    const response = await fetch(`/api/v1/employees/?${params.toString()}`);
    const data = await response.json();
    console.log(data);
}
// Example: Get a single employee by ID
async function getEmployee(employeeId) {
    const response = await fetch(`/api/v1/employees/${employeeId}`);
    const data = await response.json();
    console.log(data);
}
// Example: Get random employees
async function getRandomEmployees(num = 1) {
    const params = new URLSearchParams({ num });
    const response = await fetch(`/api/v1/employees/random?${params.toString()}`);
    const data = await response.json();
    console.log(data);
}
// Call the functions to test
listEmployees('John', 1, 5, 'salary', 'asc');
getEmployee(123);
getRandomEmployees(3);

Python

Using requests to interact with the API:

import requests
# Example: List all employees with parameters
def list_employees(search=None, page=1, limit=10, sort_by='id', sort_order='desc'):
    params = {
        'search': search,
        'page': page,
        'limit': limit,
        'sort_by': sort_by,
        'sort_order': sort_order
    }
    response = requests.get('http://localhost:8000/api/v1/employees/', params=params)
    data = response.json()
    print(data)
# Example: Get a single employee by ID
def get_employee(employee_id):
    response = requests.get(f'http://localhost:8000/api/v1/employees/{employee_id}')
    data = response.json()
    print(data)
# Example: Get random employees
def get_random_employees(num=1):
    params = {'num': num}
    response = requests.get('http://localhost:8000/api/v1/employees/random', params=params)
    data = response.json()
    print(data)
# Call the functions to test
list_employees('John', 1, 5, 'salary', 'asc')
get_employee(123)
get_random_employees(3)

Java

This example uses the HttpURLConnection class for making HTTP requests.

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class EmployeeAPIExample {
    private static final String BASE_URL = "http://localhost:8000/api/v1";
    public static void main(String[] args) throws Exception {
        // Example: List employees
        listEmployees("John", 1, 5, "salary", "asc");
        // Example: Get a single employee by ID
        getEmployee(123);
        // Example: Get random employees
        getRandomEmployees(3);
    }
    private static void listEmployees(String search, int page, int limit, String sortBy, String sortOrder) throws Exception {
        String url = BASE_URL + "/employees/?search=" + search + "&page=" + page + "&limit=" + limit + "&sort_by=" + sortBy + "&sort_order=" + sortOrder;
        sendGetRequest(url);
    }
    private static void getEmployee(int employeeId) throws Exception {
        String url = BASE_URL + "/employees/" + employeeId;
        sendGetRequest(url);
    }
    private static void getRandomEmployees(int num) throws Exception {
        String url = BASE_URL + "/employees/random?num=" + num;
        sendGetRequest(url);
    }
    private static void sendGetRequest(String url) throws Exception {
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("GET");
        int responseCode = con.getResponseCode();
        System.out.println("GET Response Code :: " + responseCode);
        if (responseCode == HttpURLConnection.HTTP_OK) { // success
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            // print result
            System.out.println(response.toString());
        } else {
            System.out.println("GET request not worked");
        }
    }
}

Swift

This example uses URLSession for making HTTP requests.

import Foundation
// Base URL
let baseURL = "http://localhost:8000/api/v1"
func listEmployees(search: String?, page: Int = 1, limit: Int = 10, sortBy: String = "id", sortOrder: String = "desc") {
    var components = URLComponents(string: "\(baseURL)/employees/")!
    var queryItems = [URLQueryItem]()
    if let search = search {
        queryItems.append(URLQueryItem(name: "search", value: search))
    }
    queryItems.append(URLQueryItem(name: "page", value: String(page)))
    queryItems.append(URLQueryItem(name: "limit", value: String(limit)))
    queryItems.append(URLQueryItem(name: "sort_by", value: sortBy))
    queryItems.append(URLQueryItem(name: "sort_order", value: sortOrder))
    components.queryItems = queryItems
    let url = components.url!
    sendGetRequest(url: url)
}
func getEmployee(employeeId: Int) {
    let url = URL(string: "\(baseURL)/employees/\(employeeId)")!
    sendGetRequest(url: url)
}
func getRandomEmployees(num: Int = 1) {
    var components = URLComponents(string: "\(baseURL)/employees/random")!
    components.queryItems = [URLQueryItem(name: "num", value: String(num))]
    
    let url = components.url!
    sendGetRequest(url: url)
}
func sendGetRequest(url: URL) {
    let task = URLSession.shared.dataTask(with: url) { data, response, error in
        guard let data = data, error == nil else {
            print("Error: \(error?.localizedDescription ?? "No data")")
            return
        }
        
        if let httpResponse = response as? HTTPURLResponse {
            print("HTTP Response Code: \(httpResponse.statusCode)")
        }
        
        if let jsonString = String(data: data, encoding: .utf8) {
            print("Response Data: \(jsonString)")
        }
    }
    task.resume()
}
// Example calls
listEmployees(search: "John", page: 1, limit: 5, sortBy: "salary", sortOrder: "asc")
getEmployee(employeeId: 123)
getRandomEmployees(num: 3)
Back to Home