Last modified: Jan 29, 2026 By Alexander Williams

Python API Number Handling Guide

Numbers are everywhere in APIs. They are IDs, prices, quantities, and status codes. Handling them correctly in Python is crucial. This guide explains how to work with numbers in your API.

We will cover validation, conversion, and serialization. You will learn to build robust and reliable services.

Why Numbers Matter in APIs

APIs exchange data between systems. Numbers are a fundamental data type. They must be accurate and consistent.

Incorrect number handling causes errors. It can lead to failed transactions or wrong calculations. Proper handling ensures your API is stable and trustworthy.

Think of an e-commerce API. It needs to process product prices and user IDs. A mistake in number parsing can be costly.

Receiving Numbers from API Requests

Data sent to an API is often text. You must convert it to a Python number. Use the int() and float() functions.

Always validate the input first. This prevents crashes from bad data.


# Example: Converting and validating a number from a request
def get_item_price(request_data):
    """
    Safely extracts a price from request data.
    """
    price_str = request_data.get('price', '0')

    try:
        # Convert string to float for decimal numbers
        price = float(price_str)
        if price < 0:
            return {"error": "Price cannot be negative"}
        return {"price": price}
    except ValueError:
        # Handle the case where conversion fails
        return {"error": "Invalid price format"}
    

# Example API call and response
# Request: {"price": "19.99"}
# Output: {"price": 19.99}

# Request: {"price": "nineteen"}
# Output: {"error": "Invalid price format"}
    

Sending Numbers in API Responses

Your API must send data back. Python objects like integers and floats need to be serialized. Convert them to JSON-friendly formats.

JSON does not support all Python number types. Use the json.dumps() method for conversion.


import json

# Example: Preparing a response with numbers
def get_inventory_response():
    """
    Creates a JSON response containing various number types.
    """
    inventory_data = {
        "item_id": 4501,          # Integer
        "price": 24.95,           # Float
        "quantity_in_stock": 150, # Integer
        "is_available": True
    }

    # Serialize the dictionary to a JSON string
    json_response = json.dumps(inventory_data)
    return json_response
    

# Output JSON string
{"item_id": 4501, "price": 24.95, "quantity_in_stock": 150, "is_available": true}
    

Validating Number Ranges and Types

Not every number is valid for your application. You must check if a number is within an acceptable range.

For example, a quantity should be a positive integer. A percentage should be between 0 and 100.

Use simple if statements or validation libraries. This ensures data integrity.


# Example: Advanced number validation
def validate_discount_code(data):
    """
    Validates a discount code with a percentage value.
    """
    code = data.get('code')
    percentage = data.get('percentage')

    # Type and presence check
    if not isinstance(percentage, (int, float)):
        return {"valid": False, "message": "Percentage must be a number"}

    # Range validation
    if not (0 <= percentage <= 100):
        return {"valid": False, "message": "Percentage must be between 0 and 100"}

    # Check if it's a whole number for percentage
    if percentage != int(percentage):
        return {"valid": False, "message": "Percentage should be a whole number"}

    return {"valid": True, "code": code, "percentage": int(percentage)}
    

Common Pitfalls and How to Avoid Them

Developers face common issues with API numbers. Being aware of them saves time.

Floating-Point Precision: Float calculations can have tiny errors. For money, use the decimal module.

Large Integers: JSON in some systems may not handle very large integers. Ensure your client libraries support them.

Type Confusion: A number might arrive as a string '123' or a number 123. Always standardize your input.

Integrating Number Handling in Larger Projects

In big applications, you don't write validation for every endpoint. Use frameworks and schemas.

For building REST APIs, consider using Flask-RESTful. It helps structure requests and responses. You can learn more in our guide on how to Install Flask-RESTful for Python API Development.

When automating tasks with other services, numbers are key. For instance, if you need to Automate GitLab with Python API Guide, you'll be handling issue IDs and merge request numbers.

Similarly, working with spatial data in a Master GIS with ArcGIS Python API project involves precise coordinates and measurements.

Best Practices Summary

Follow these rules for solid number handling.

Always validate and convert incoming string numbers. Use try-except blocks to catch errors.

Be explicit about number types in your API documentation. State if a field is an integer or a float.

Use the right numeric type for the job. Use integers for counts and IDs. Use Decimal for financial values.

Test edge cases. Test with very large numbers, zero, and negative values.

Conclusion

Handling numbers in a Python API is a core skill. It involves validation, conversion, and careful serialization.

By using try-except blocks, type checking, and range validation, you build reliable services. Remember the pitfalls like floating-point precision.

Integrate these practices into your workflow. Your APIs will be more robust and easier to maintain. Start applying these techniques in your next project.