Automated summary
Guides the creation of custom Python data sources for Apache Spark 4.0+ using the PySpark DataSource API, for both batch and streaming reads and writes.
Strengths
- Covers all four modes (batch and streaming read/write) with a flat inheritance structure suited to PySpark serialization
- Surfaces real driver/executor constraints, such as importing third-party libraries inside methods that run on workers
- Offers concrete partitioning strategies (time-based, token-range, ID-range) plus a project layout with pytest-spark tests
- Emphasizes minimal dependencies, which matters because every package must be installed on all executor nodes
Limitations
- Assumes prior familiarity with Spark, the driver/executor model, and the DataSource API
- Does not include a complete ready-to-run implementation in the SKILL.md itself; most detail lives in external reference files
- The authentication section is cut off and remains thinly specified
Reach for it when no native connector exists and you need to read from or write to an external system from Spark in Python.
Skip it if an existing Spark connector (JDBC, Kafka, Delta, etc.) already covers the need, or if the work is in Scala/Java.
Security analysis
SafeThis skill is pure instructional documentation for building PySpark DataSource connectors. It contains no executable commands beyond benign developer tooling (uv init, pytest, ruff), no destructive operations, no network exfiltration, no credential harvesting, and no safety-disabling instructions. The auth guidance discusses credential patterns abstractly but never instructs sending secrets anywhere. Execution risk is negligible.
No concerns found
How this analysis is madeExamples
I need to read data from our internal REST API into a Spark DataFrame, but there's no native connector. Can you build a PySpark batch data source with pagination?Write a PySpark streaming data source that pushes rows from a Structured Streaming query into our custom queue system.Build a Spark Python data source that reads from our Postgres table in parallel — partition by ID range and keep the dependencies minimal.name: spark-python-data-source description: Build custom Python data sources for Apache Spark using the PySpark DataSource API — batch and streaming readers/writers for external systems. Use this skill whenever someone wants to connect Spark to an external system (database, API, message queue, custom protocol), build a Spark connector or plugin in Python, implement a DataSourceReader or DataSourceWriter, pull data from or push data to a system via Spark, or work with the PySpark DataSource API in any way. Even if they just say "read from X in Spark" or "write DataFrame to Y" and there's no native connector, this skill applies.
spark-python-data-source
Build custom Python data sources for Apache Spark 4.0+ to read from and write to external systems in batch and streaming modes.
Instructions
You are an experienced Spark developer building custom Python data sources using the PySpark DataSource API. Follow these principles and patterns.
Core Architecture
Each data source follows a flat, single-level inheritance structure:
- DataSource class — entry point that returns readers/writers
- Base Reader/Writer classes — shared logic for options and data processing
- Batch classes — inherit from base +
DataSourceReader/DataSourceWriter - Stream classes — inherit from base +
DataSourceStreamReader/DataSourceStreamWriter
See implementation-template.md for the full annotated skeleton covering all four modes (batch read/write, stream read/write).
Spark-Specific Design Constraints
These are specific to the PySpark DataSource API and its driver/executor architecture — general Python best practices (clean code, minimal dependencies, no premature abstraction) still apply but aren't repeated here.
Flat single-level inheritance only. PySpark serializes reader/writer instances to ship them to executors. Complex inheritance hierarchies and abstract base classes break serialization and make cross-process debugging painful. Use one shared base class mixed with the PySpark interface (e.g., class YourBatchWriter(YourWriter, DataSourceWriter)).
Import third-party libraries inside executor methods. The read() and write() methods run on remote executor processes that don't share the driver's Python environment. Top-level imports from the driver won't be available on executors — always import libraries like requests or database drivers inside the methods that run on workers.
Minimize dependencies. Every package you add must be installed on all executor nodes in the cluster, not just the driver. Prefer the standard library; when external packages are needed, keep them few and well-known.
No async/await unless the external system's SDK is async-only. The PySpark DataSource API is synchronous, so async adds complexity with no benefit.
Project Setup
Create a Python project using a packaging tool such as uv, poetry, or hatch. Examples use uv (substitute your tool of choice):
uv init your-datasource
cd your-datasource
uv add pyspark pytest pytest-spark
your-datasource/
├── pyproject.toml
├── src/
│ └── your_datasource/
│ ├── __init__.py
│ └── datasource.py
└── tests/
├── conftest.py
└── test_datasource.py
Run all commands through the packaging tool so they execute within the correct virtual environment:
uv run pytest # Run tests
uv run ruff check src/ # Lint
uv run ruff format src/ # Format
uv build # Build wheel
Key Implementation Decisions
Partitioning Strategy — choose based on data source characteristics:
- Time-based: for APIs with temporal data
- Token-range: for distributed databases
- ID-range: for paginated APIs
- See partitioning-patterns.md for implementations of each strategy
Authentication — support multiple methods in priority order:
- Databricks Unity Catalog credentials
- Cloud default credentials (managed identity)
- Explicit credentials (service principal, API key, username/password)
- See authentication-patterns.md for patterns with fallback chains
Type Conversion — map between Spark and external types:
- Handle nulls, timestamps, UUIDs, collections
- See type-conversion.md for bidirectional mapping tables and helpers
Streaming Offsets — design for exactly-once semantics:
- JSON-serializable offset class
- Non-overlapping partition boundaries
- See streaming-patterns.md for offset tracking and watermark patterns
Error Handling — implement retries and resilience:
- Exponential backoff for transient failures (network, rate limits)
- Circuit breakers for cascading failures
- See error-handling.md for retry decorators and failure classification
Testing
import pytest
from unittest.mock import patch, Mock
@pytest.fixture
def spark():
from pyspark.sql import SparkSession
return SparkSession.builder.master("local[2]").getOrCreate()
def test_data_source_name():
assert YourDataSource.name() == "your-format"
def test_writer_sends_data(spark):
with patch('requests.post') as mock_post:
mock_post.return_value = Mock(status_code=200)
df = spark.createDataFrame([(1, "test")], ["id", "value"])
df.write.format("your-format").option("url", "http://api").save()
assert mock_post.called
See testing-patterns.md for unit/integration test patterns, fixtures, and running tests.
Reference Implementations
Study these for real-world patterns:
- cyber-spark-data-connectors — Sentinel, Splunk, REST
- spark-cassandra-data-source — Token-range partitioning
- pyspark-hubspot — REST API pagination
- pyspark-mqtt — Streaming with TLS
Example Prompts
Create a Spark data source for reading from MongoDB with sharding support
Build a streaming connector for RabbitMQ with at-least-once delivery
Implement a batch writer for Snowflake with staged uploads
Write a data source for REST API with OAuth2 authentication and pagination
Related
- databricks-testing: Test data sources on Databricks clusters
- databricks-spark-declarative-pipelines: Use custom sources in DLT pipelines
- python-dev: Python development best practices
References
- implementation-template.md — Full annotated skeleton; read when starting a new data source
- partitioning-patterns.md — Read when the source supports parallel reads and you need to split work across executors
- authentication-patterns.md — Read when the external system requires credentials or tokens
- type-conversion.md — Read when mapping between Spark types and the external system's type system
- streaming-patterns.md — Read when implementing
DataSourceStreamReaderorDataSourceStreamWriter - error-handling.md — Read when adding retry logic or handling transient failures
- testing-patterns.md — Read when writing tests; covers unit, integration, and performance testing
- production-patterns.md — Read when hardening for production: observability, security, input validation
- Official Databricks Documentation
- Apache Spark Python DataSource Tutorial
- awesome-python-datasources — Directory of community implementations
From the file to a first result
The download contains exactly the content displayed on this page. This copy may differ from the latest version in the source repository.
View the source and supporting filesThis download contains SKILL.md only. Any scripts, references, templates and dependencies are not included. Get the required files from the source, preserving their directory structure, before continuing.
1. Download the file
Download SKILL.mdFrom the root of a test project, save the file as .skill-downloads/spark-python-data-source-ms1aw5n1/SKILL.md, or use the command below. This folder is for inspecting the skill before installation.
Command for macOS/Linux or WSL: requires a POSIX shell and curl. On Windows without WSL, use the download button and create the folder manually.
mkdir -p '.skill-downloads/spark-python-data-source-ms1aw5n1' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/spark-python-data-source-ms1aw5n1/download' --output '.skill-downloads/spark-python-data-source-ms1aw5n1/SKILL.md.part' && mv '.skill-downloads/spark-python-data-source-ms1aw5n1/SKILL.md.part' '.skill-downloads/spark-python-data-source-ms1aw5n1/SKILL.md'2. Check prerequisites
Read SKILL.md before using it. If it references scripts or external services, inspect them and prepare the required access in your test environment.
No recognized prerequisites section in this file. This does not mean it is self-contained: libraries, tools and access requirements may be mentioned elsewhere in the content or source repository.
The platforms on this page are catalog indications. The paths below follow tool documentation; they do not prove this skill has been run in those tools. No minimum tool version is confirmed for this listing.
3. Load the skill
After inspection, copy the complete folder into your project using one of the commands below, then open a new tool session. The command stops if a folder with the same name already exists: compare the files before replacing it.
Claude Code
test -f '.skill-downloads/spark-python-data-source-ms1aw5n1/SKILL.md' && test -s '.skill-downloads/spark-python-data-source-ms1aw5n1/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/spark-python-data-source' && cp -R '.skill-downloads/spark-python-data-source-ms1aw5n1' '.claude/skills/spark-python-data-source'Cursor
test -f '.skill-downloads/spark-python-data-source-ms1aw5n1/SKILL.md' && test -s '.skill-downloads/spark-python-data-source-ms1aw5n1/SKILL.md' && mkdir -p '.cursor/skills' && test ! -e '.cursor/skills/spark-python-data-source' && cp -R '.skill-downloads/spark-python-data-source-ms1aw5n1' '.cursor/skills/spark-python-data-source'Codex
test -f '.skill-downloads/spark-python-data-source-ms1aw5n1/SKILL.md' && test -s '.skill-downloads/spark-python-data-source-ms1aw5n1/SKILL.md' && mkdir -p '.agents/skills' && test ! -e '.agents/skills/spark-python-data-source' && cp -R '.skill-downloads/spark-python-data-source-ms1aw5n1' '.agents/skills/spark-python-data-source'OpenSkills
OpenSkills must already be installed. The local install/read procedure is checked with OpenSkills 1.5.0, which requires Node.js ≥ 20.6.0. Catalog slugs are not resolved automatically.
Official OpenSkills installationopenskills install './.skill-downloads/spark-python-data-source-ms1aw5n1'openskills read 'spark-python-data-source-ms1aw5n1'Reading should display the installed file content and its base directory. It does not run the skill or install its dependencies.
For an agent that reads AGENTS.md, then sync the index. This command changes AGENTS.md: review the diff before using it.
openskills syncManual method or another tool: attach SKILL.md to a conversation, or open it in an agent that can read files. Include any required supporting resources. No universal folder is recognized by every tool.
4. Try a first task
Use a short, synthetic input: an API endpoint, a small document or an interface brief. In a new conversation, attach the file or give the agent its path, then adapt this request:
Read .skill-downloads/spark-python-data-source-ms1aw5n1/SKILL.md and apply its instructions to this example: [describe a test input]. Identify any missing files, dependencies or access. Produce the result requested by the skill without inventing data or running unreviewed scripts.Expected result: output matching the skill instructions, or a precise list of missing prerequisites. A read confirmation alone does not validate a first use. If an external resource is unavailable, that path remains untested.
Create Interactive Maps with kepler.gl
Data & AI
Create interactive map visualizations and export standalone HTML using the keplergl Python package. Use to plot geospatial data from DataFrames, GeoJSON, or CSV.
Agent-Driven Parameter Optimization
Data & AI
Guide for optimizing configurable systems with a measurable objective, using bounded trials and evidence-based recommendations.
ICP Visitor Outreach
Data & AI
Identify signed-up users matching the ideal customer profile but stalled, and draft personalized outreach to re-engage them.