Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .env
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
GOOGLE_API_KEY=AIzaSyC6y93Jo0fA1GH54L7VOkJzgZkiaXSSOOU
17 changes: 17 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
name: CI

on:
pull_request:
branches: [main]

jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
cache: npm
- run: npm ci
- run: npm test
132 changes: 131 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,131 @@
.DS_Store
.DS_Store

# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*

# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage
*.lcov

# nyc test coverage
.nyc_output

# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# Snowpack dependency directory (https://snowpack.dev/)
web_modules/

# TypeScript cache
*.tsbuildinfo

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional stylelint cache
.stylelintcache

# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variable files
.env.development.local
.env.test.local
.env.production.local
.env.local

# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache

# Next.js build output
.next
out

# Nuxt.js build / generate output
.nuxt
dist

# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public

# vuepress build output
.vuepress/dist

# vuepress v2.x temp and cache directory
.temp
.cache

# Docusaurus cache and generated files
.docusaurus

# Serverless directories
.serverless/

# FuseBox cache
.fusebox/

# DynamoDB Local files
.dynamodb/

# TernJS port file
.tern-port

# Stores VSCode versions used for testing VSCode extensions
.vscode-test

# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*
10 changes: 10 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# Repository Guidelines

- Hosted on Netlify.
- Install new packages when needed.
- JSON files use two-space indentation.
- `public` should contain all public assets.
- Serverless functions are in `netlify/edge-functions`.
- Keep README and AGENTS.md updated when changes are made
- Pull requests to `main` run `npm test` via GitHub Actions.
- Tests are located in `test` and run with `npm test`.
7 changes: 7 additions & 0 deletions LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Copyright 2025 Patrick Tobias

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
40 changes: 40 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,42 @@
# google-sheets-api

An API that converts Google Sheets into JSON, served via a Netlify Edge Function.

Visiting the root URL shows a form where you can paste a Google Sheets link. The form rewrites the link to a valid API URL and redirects you there.

## Usage

Requests follow the pattern `/SPREADSHEET_ID/sheet_name_or_number`. If the sheet
segment is omitted, the request will redirect to the first sheet (`/1`).

Example:

```
https://sheets-json-api.netlify.app/1vufOODlks7O9PGak54hMNP4LWBUAoP-XB9n3VW_aw5Y
```

This redirects to:

```
https://sheets-json-api.netlify.app/1vufOODlks7O9PGak54hMNP4LWBUAoP-XB9n3VW_aw5Y/1
```

## Development

The Edge Function lives in `netlify/edge-functions/opensheet.ts`.

### Running tests

```sh
npm test
```

Tests fetch a sample spreadsheet and verify rows are returned, ensure the deployed API returns `[{"headline":"It's working!"}]`, and confirm that requests missing a sheet segment redirect to the first sheet.

### Continuous integration

Pull requests to `main` run `npm test` via GitHub Actions.

## Deployment

Netlify builds read `netlify.toml` and publish files from `public`.
7 changes: 7 additions & 0 deletions netlify.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# Route all paths to the Edge Function
[[edge_functions]]
function = "opensheet"
path = "/*"

[build]
publish = "public"
120 changes: 120 additions & 0 deletions netlify/edge-functions/opensheet.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
// netlify/edge-functions/opensheet.ts

import type { Context } from "@netlify/edge-functions";

export default async function handler(request: Request, context: Context) {
const GOOGLE_API_KEY = process.env.GOOGLE_API_KEY?.trim() || "AIzaSyC6y93Jo0fA1GH54L7VOkJzgZkiaXSSOOU";
if (!GOOGLE_API_KEY) {
return error("Missing GOOGLE_API_KEY environment variable", 500);
}

const url = new URL(request.url);

if (url.pathname === "/") {
return context.next();
}

let [id, sheet, ...otherParams] = url.pathname
.slice(1)
.split("/")
.filter((x) => x);

if (!id) {
return error("URL format is /spreadsheet_id/sheet_name", 404);
}

if (!sheet) {
return Response.redirect(`${url.origin}/${id}/1`, 302);
}

if (otherParams.length > 0) {
return error("URL format is /spreadsheet_id/sheet_name", 404);
}

// Try cache first (Edge Cache API)
const cacheKey = `https://sheets-json-api.netlify.app/${id}/${encodeURIComponent(sheet)}`;
const cache = caches.default;
const cachedResponse = await cache.match(cacheKey);
if (cachedResponse) {
console.log(`Serving from cache: ${cacheKey}`);
return cachedResponse;
} else {
console.log(`Cache miss: ${cacheKey}`);
}

// Normalize sheet (handle '+' and decode)
sheet = decodeURIComponent(sheet.replace(/\+/g, " "));

// If numeric, treat as 1-based sheet index and look up sheet title
if (!isNaN(sheet as unknown as number)) {
if (parseInt(sheet, 10) === 0) {
return error("For this API, sheet numbers start at 1");
}

const sheetMetaRes = await fetch(
`https://sheets.googleapis.com/v4/spreadsheets/${id}?key=${GOOGLE_API_KEY}`
);
const sheetData = await sheetMetaRes.json();

if (sheetData?.error) {
return error(sheetData.error.message, sheetMetaRes.status || 400);
}

const sheetIndex = parseInt(sheet, 10) - 1;
const sheetWithThisIndex = sheetData.sheets?.[sheetIndex];

if (!sheetWithThisIndex) {
return error(`There is no sheet number ${sheet}`);
}

sheet = sheetWithThisIndex.properties.title;
}

const valuesRes = await fetch(
`https://sheets.googleapis.com/v4/spreadsheets/${id}/values/${encodeURIComponent(
sheet
)}?key=${GOOGLE_API_KEY}`
);
const result = await valuesRes.json();

if (result?.error) {
return error(result.error.message, valuesRes.status || 400);
}

const rows: Record<string, string>[] = [];
const rawRows: string[][] = result.values || [];
const headers: string[] = rawRows.shift() || [];

rawRows.forEach((row) => {
const rowData: Record<string, string> = {};
row.forEach((item, index) => {
rowData[headers[index]] = item;
});
rows.push(rowData);
});

const apiResponse = new Response(JSON.stringify(rows), {
headers: {
"Content-Type": "application/json",
"Cache-Control": "s-maxage=30",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept",
},
});

// Write to cache in the background
context.waitUntil(cache.put(cacheKey, apiResponse.clone()));

return apiResponse;
}

function error(message: string, status = 400) {
return new Response(JSON.stringify({ error: message }), {
status,
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept",
},
});
}
Loading