or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

authentication.mdchangesets.mderrors.mdindex.mdnodes.mdnotes.mdrelations.mdways.md
tile.json

tessl/pypi-osmapi

Python wrapper for the OSM API

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/osmapi@4.3.x

To install, run

npx @tessl/cli install tessl/pypi-osmapi@4.3.0

index.mddocs/

osmapi

Python wrapper for the OpenStreetMap (OSM) API that enables developers to programmatically interact with OpenStreetMap data and services. It provides full CRUD operations for OSM elements (nodes, ways, relations), changeset management, OAuth 2.0 authentication support, and robust error handling for API interactions. The library is designed for maximum usability in GIS applications, data analysis tools, mapping software, and automated OSM editing workflows.

Package Information

  • Package Name: osmapi
  • Language: Python
  • Installation: pip install osmapi
  • Requirements: Python >= 3.8, requests library

Core Imports

import osmapi

Common pattern with main API class:

import osmapi
api = osmapi.OsmApi()

Import specific error classes:

from osmapi import ElementNotFoundApiError, ApiError

Basic Usage

import osmapi

# Read data (no authentication required)
api = osmapi.OsmApi()
node = api.NodeGet(123)
print(f"Node {node['id']} at ({node['lat']}, {node['lon']})")

# Download map data in a bounding box
map_data = api.Map(min_lon=-122.35, min_lat=47.60, max_lon=-122.30, max_lat=47.63)
print(f"Downloaded {len(map_data)} elements")
for element in map_data[:3]:  # Show first 3 elements
    print(f"  {element['type']} {element['data']['id']}")

# Write data (authentication required)
api = osmapi.OsmApi(username="your_username", password="your_password")
with api.Changeset({"comment": "Adding new nodes"}) as changeset_id:
    # Create a new node
    new_node = api.NodeCreate({
        "lat": 47.6062,
        "lon": -122.3321,
        "tag": {"name": "Seattle Center", "amenity": "attraction"}
    })
    print(f"Created node {new_node['id']}")

Architecture

The osmapi library follows a comprehensive design pattern:

  • OsmApi Class: Main interface providing all OpenStreetMap API operations
  • Session Management: HTTP session handling with automatic retry logic and connection pooling
  • Authentication: Support for basic auth, OAuth 2.0, and custom session objects
  • Changeset Management: Automatic or manual changeset handling for data modifications
  • Error Hierarchy: Comprehensive exception classes for different API error scenarios
  • XML Processing: Built-in parsing and generation of OSM XML formats
  • Data Validation: Type checking and validation for OSM data structures

Capabilities

Node Operations

Complete CRUD operations for OSM nodes including creation, retrieval, updating, deletion, and history tracking. Supports bulk operations and relationship queries.

def NodeGet(NodeId, NodeVersion=-1): ...
def NodeCreate(NodeData): ...
def NodeUpdate(NodeData): ...
def NodeDelete(NodeData): ...
def NodeHistory(NodeId): ...
def NodeWays(NodeId): ...
def NodeRelations(NodeId): ...
def NodesGet(NodeIdList): ...

Node Operations

Way Operations

Full lifecycle management for OSM ways including creation with node references, modification, deletion, and relationship tracking. Supports bulk operations and full data retrieval.

def WayGet(WayId, WayVersion=-1): ...
def WayCreate(WayData): ...
def WayUpdate(WayData): ...
def WayDelete(WayData): ...
def WayHistory(WayId): ...
def WayRelations(WayId): ...
def WayFull(WayId): ...
def WaysGet(WayIdList): ...

Way Operations

Relation Operations

Comprehensive relation management including creation, modification, deletion, and nested relation handling. Supports both two-level and recursive full data retrieval.

def RelationGet(RelationId, RelationVersion=-1): ...
def RelationCreate(RelationData): ...
def RelationUpdate(RelationData): ...
def RelationDelete(RelationData): ...
def RelationHistory(RelationId): ...
def RelationRelations(RelationId): ...
def RelationFull(RelationId): ...
def RelationFullRecur(RelationId): ...
def RelationsGet(RelationIdList): ...

Relation Operations

Changeset Management

Complete changeset lifecycle including creation, modification, closure, and discussion management. Supports both automatic and manual changeset handling with batch uploads.

@contextmanager
def Changeset(ChangesetTags={}): ...
def ChangesetGet(ChangesetId, include_discussion=False): ...
def ChangesetCreate(ChangesetTags={}): ...
def ChangesetUpdate(ChangesetTags={}): ...
def ChangesetClose(): ...
def ChangesetUpload(ChangesData): ...
def ChangesetDownload(ChangesetId): ...
def ChangesetsGet(**filters): ...
def ChangesetComment(ChangesetId, comment): ...
def ChangesetSubscribe(ChangesetId): ...
def ChangesetUnsubscribe(ChangesetId): ...

Changeset Management

Notes Operations

Full Notes API support including creation, commenting, status management, and search functionality. Enables community interaction and issue reporting.

def NotesGet(min_lon, min_lat, max_lon, max_lat, limit=100, closed=7): ...
def NoteGet(id): ...
def NoteCreate(NoteData): ...
def NoteComment(NoteId, comment): ...
def NoteClose(NoteId, comment): ...
def NoteReopen(NoteId, comment): ...
def NotesSearch(query, limit=100, closed=7): ...

Notes Operations

Map Data Download

Download OSM data within a specified bounding box, returning all elements (nodes, ways, relations) in that area for offline processing or analysis.

def Map(min_lon, min_lat, max_lon, max_lat): ...

Authentication & Configuration

Multiple authentication methods including basic auth, OAuth 2.0, and custom session handling. Supports both production and development OSM servers.

class OsmApi:
    def __init__(
        self,
        username=None,
        password=None,
        passwordfile=None,
        appid="",
        created_by="osmapi/4.3.0",
        api="https://www.openstreetmap.org",
        changesetauto=False,
        changesetautotags={},
        changesetautosize=500,
        changesetautomulti=1,
        session=None,
        timeout=30,
    ): ...

Authentication & Configuration

Error Handling

Comprehensive error hierarchy covering all API scenarios including network errors, authentication failures, data conflicts, and OSM-specific exceptions.

class OsmApiError(Exception): ...
class ApiError(OsmApiError): ...
class UsernamePasswordMissingError(OsmApiError): ...
class ElementNotFoundApiError(ApiError): ...
class ElementDeletedApiError(ApiError): ...
class VersionMismatchApiError(ApiError): ...
# ... 15+ additional error classes

Error Handling

Types

Core Data Structures

# Node data structure
NodeData = {
    'id': int,           # Node ID (for existing nodes)
    'lat': float,        # Latitude (required)
    'lon': float,        # Longitude (required)
    'tag': dict,         # Key-value tags
    'version': int,      # Version number
    'changeset': int,    # Changeset ID
    'user': str,         # Username
    'uid': int,          # User ID
    'timestamp': str,    # ISO timestamp
    'visible': bool      # Visibility flag
}

# Way data structure  
WayData = {
    'id': int,           # Way ID (for existing ways)
    'nd': list[int],     # List of node IDs (required)
    'tag': dict,         # Key-value tags
    'version': int,      # Version number
    'changeset': int,    # Changeset ID
    'user': str,         # Username
    'uid': int,          # User ID
    'timestamp': str,    # ISO timestamp
    'visible': bool      # Visibility flag
}

# Relation data structure
RelationData = {
    'id': int,           # Relation ID (for existing relations)
    'member': list[dict], # List of member objects (required)
    'tag': dict,         # Key-value tags
    'version': int,      # Version number
    'changeset': int,    # Changeset ID
    'user': str,         # Username
    'uid': int,          # User ID
    'timestamp': str,    # ISO timestamp
    'visible': bool      # Visibility flag
}

# Relation member structure
RelationMember = {
    'type': str,         # 'node', 'way', or 'relation'
    'ref': int,          # Referenced element ID
    'role': str          # Role description
}

# Note data structure
NoteData = {
    'id': int,           # Note ID
    'lat': float,        # Latitude
    'lon': float,        # Longitude
    'text': str,         # Note text
    'status': str,       # 'open' or 'closed'
    'date_created': str, # Creation timestamp
    'date_closed': str,  # Closure timestamp (or None)
    'uid': int,          # User ID (or None)
    'user': str,         # Username (or None)
    'comments': list[dict] # List of comment objects
}