I have an 11ty website that I regularly update. I'd like to create an iOS app that gets its content via a JSON api that's generated by the 11ty website, and is updated any time new content is available. What's the best way to generate that JSON API in 11ty. Please show any configuration, javascript or template code needed. Only on the 11ty side. I don't need help on the iOS side right now.
I have 3 relevant collections that I'll want to include APIs for:
// Sort collections by date in descending order
eleventyConfig.addCollection("story", function(collectionApi) {
return collectionApi.getFilteredByTag("story")
.sort((a, b) => new Date(b.date) - new Date(a.date));
});
eleventyConfig.addCollection("post-match", function(collectionApi) {
return collectionApi.getFilteredByTag("post-match")
.sort((a, b) => new Date(b.date) - new Date(a.date));
});
eleventyConfig.addCollection("pre-match", function(collectionApi) {
return collectionApi.getFilteredByTag("pre-match")
.sort((a, b) => new Date(b.date) - new Date(a.date));
});
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
To generate a JSON API for your 11ty website based on your three collections ("story", "post-match", and "pre-match"), you can create dedicated JSON output files. These files will be processed by 11ty during the build process and will contain the data from your collections in JSON format.
The key steps are:
Leverage your existing collections: Your collections are already defined in your .eleventy.js configuration file, so you can access them directly in your JSON template files.
Create JSON template files: Use 11ty's JavaScript template files (e.g., .11ty.js) to generate JSON output. In these files, you'll access the collections, process the data if needed (e.g., select only relevant fields), and output the JSON string.
Set permalinks: Configure each file to output as a .json file in a specific path, like /api/stories.json, so your iOS app can fetch from these endpoints.
Ensure updates: Whenever you rebuild your 11ty site (e.g., via a deployment script), the JSON files will be regenerated based on the latest content, reflecting any changes to your collections.
Here's how to implement this:
1. Update Your .eleventy.js Configuration (if needed)
Your collections are already set up correctly in your .eleventy.js file. No changes are required here, but for completeness, here's a reminder of what you have:
javascript
const eleventyConfig = require('@11ty/eleventy');
module.exports = function(eleventyConfig) {
// Your existing collections
eleventyConfig.addCollection("story", function(collectionApi) {
return collectionApi.getFilteredByTag("story")
.sort((a, b) => new Date(b.date) - new Date(a.date));
});
eleventyConfig.addCollection("post-match", function(collectionApi) {
return collectionApi.getFilteredByTag("post-match")
.sort((a, b) => new Date(b.date) - new Date(a.date));
});
eleventyConfig.addCollection("pre-match", function(collectionApi) {
return collectionApi.getFilteredByTag("pre-match")
.sort((a, b) => new Date(b.date) - new Date(a.date));
});
// Other configurations...
return {
dir: {
input: 'src', // Assuming your input directory is 'src'
output: 'dist' // Assuming your output directory is 'dist'
}
};
};
2. Create JSON Template Files
In your project's input directory (e.g., src/), create a new directory called api/ (or whatever you prefer, as long as it matches your permalink paths). Inside this directory, add one .11ty.js file for each collection. These files will generate the JSON output.
For example:
src/api/stories.11ty.js for the "story" collection.
src/api/post-matches.11ty.js for the "post-match" collection.
src/api/pre-matches.11ty.js for the "pre-match" collection.
Each file will use front matter to set the permalink and then export a function that processes the collection data and returns the JSON string.
Example: src/api/stories.11ty.js
javascript
---
permalink: /api/stories.json
eleventyExcludeFromCollections: true // Optional: Prevents this file from being added to collections
---
module.exports = function(data) {
// Access the 'story' collection
const stories = data.collections.story;
// Map the collection to a simplified array of objects
// Only include the fields you want to expose in the API
const processedStories = stories.map(item => ({
title: item.data.title, // Assuming your items have a 'title' in front matter
date: item.date ? item.date.toISOString() : null, // Convert date to ISO string
excerpt: item.data.excerpt, // Assuming you have an excerpt
url: item.url, // 11ty's generated URL for the item
// Add any other fields from item.data as needed, e.g., item.data.author
}));
// Return the JSON string
return JSON.stringify(processedStories, null, 2); // Pretty-print with 2 spaces indentation
};
Front Matter: The --- block at the top sets the permalink to define the output file path (e.g., /api/stories.json in the build directory). The eleventyExcludeFromCollections: true option ensures these files aren't included in any collections, keeping your build clean.
Accessing Collections: In the exported function, the data parameter provides access to data.collections, which includes your defined collections. For collections with hyphens (e.g., "post-match"), use bracket notation like data.collections['post-match'].
Processing Data: The map() function transforms each item in the collection into a simplified object. This is where you control what data gets exposed in the JSON API. For example:
item.data.title: Accesses front matter fields.
item.date: The date from the collection (already sorted).
item.url: 11ty's generated URL for the item, which can be useful for linking back to the web version.
You can add or remove fields based on what your iOS app needs.
Outputting JSON: JSON.stringify() converts the array of objects to a JSON string. The null, 2 parameters make the output human-readable (indented with 2 spaces), which is helpful for debugging.
Sorting: Your collections are already sorted in descending order by date in the configuration, so no additional sorting is needed here.
3. Build and Verify
When you run npx @11ty/eleventy or your build command, 11ty will process these files and output the JSON files to your output directory (e.g., dist/api/stories.json).
The resulting URLs will be something like https://yourwebsite.com/api/stories.json, assuming your site is served from the root.
To test, build your site and check the generated JSON files in the output directory. You can also use a tool like curl or a browser to fetch the files after deploying.
Additional Tips
Security Considerations: Be mindful of what data you expose in the JSON. For instance, avoid including sensitive information like full content or private metadata.
Performance: If your collections are large, consider adding pagination or filtering in these templates if needed (e.g., limit to the latest 50 items).
Updates: The JSON files will automatically update on every build. Set up a CI/CD pipeline (e.g., with GitHub Actions or Netlify) to rebuild your site whenever content changes, ensuring the API stays current.
Error Handling: If a collection is empty, the output will be an empty array [], which is fine for most APIs.
Customization: If you need to add more logic (e.g., filtering by date or combining collections), you can extend the mapping function.
This setup keeps everything within 11ty and ensures your JSON API is generated efficiently. If you encounter any issues, double-check that your collections are populating correctly by logging them during development.
User
I forgot to mention, I want to do as much as possible using .liquid files
Assistant
I understand you'd prefer to use .liquid files for generating your JSON APIs in 11ty. That's a great choice since 11ty supports Liquid templates for any output type, including JSON. By setting the permalink to end in .json, 11ty will treat the output as a JSON file, and you can construct the JSON structure directly in the Liquid template.
Here's how to adapt the previous setup to use .liquid files. We'll create one .liquid file for each of your collections ("story", "post-match", and "pre-match"). In these files, we'll:
Use front matter to set the permalink (e.g., /api/stories.json).
Access the collections via site.collections (e.g., site.collections.story).
Use Liquid loops and filters to process the data and output a valid JSON array.
Leverage Liquid's jsonify filter (or json in some setups) to properly escape and format strings for JSON output.
Key Considerations for Liquid Templates
Accessing Collections: In Liquid, collections are available as site.collections.<collectionName>. For collections with hyphens (e.g., "post-match"), use bracket notation: site.collections['post-match'].
Processing Data: Your collections are already sorted by date in descending order in your .eleventy.js config, so no additional sorting is needed. We'll use a Liquid loop (for) to iterate over the items and build a JSON array.
Outputting JSON: Construct the JSON string manually in the template. Use Liquid filters like jsonify to ensure strings are properly quoted and escaped. For dates, use filters like date_to_iso8601 or manual formatting to convert them to ISO strings.
File Structure: Place these .liquid files in your input directory, e.g., src/api/stories.liquid.
Excluding from Collections: Add eleventyExcludeFromCollections: true in the front matter to prevent these files from being added to any collections.
Step 1: Create the .liquid Files
In your project's input directory (e.g., src/), create a new directory called api/ and add the following files:
Explanation: Same structure, but for the "pre-match" collection.
Step 2: Verify Your .eleventy.js Configuration
Your existing configuration in .eleventy.js remains unchanged. It defines the collections, which are now accessible in your Liquid templates via site.collections. Here's a quick reminder:
javascript
const eleventyConfig = require('@11ty/eleventy');
module.exports = function(eleventyConfig) {
eleventyConfig.addCollection("story", function(collectionApi) {
return collectionApi.getFilteredByTag("story")
.sort((a, b) => new Date(b.date) - new Date(a.date));
});
eleventyConfig.addCollection("post-match", function(collectionApi) {
return collectionApi.getFilteredByTag("post-match")
.sort((a, b) => new Date(b.date) - new Date(a.date));
});
eleventyConfig.addCollection("pre-match", function(collectionApi) {
return collectionApi.getFilteredByTag("pre-match")
.sort((a, b) => new Date(b.date) - new Date(a.date));
});
return {
dir: {
input: 'src',
output: 'dist'
}
};
};
Step 3: Build and Test
Run your 11ty build command: npx @11ty/eleventy.
This will generate the JSON files in your output directory (e.g., dist/api/stories.json).
Verify the output:
Open the generated files (e.g., dist/api/stories.json) in a text editor or use a JSON validator to ensure they are valid JSON.
If deployed, access them via URLs like https://yourwebsite.com/api/stories.json.
If you encounter issues with date formatting or missing fields, double-check your front matter in the original content files and adjust the Liquid filters as needed.
Additional Tips
Customizing Fields: In the Liquid loops, you can add or remove fields based on your iOS app's needs. For example, if you have other front matter fields like author, add "author": {{ item.data.author | jsonify }}.
Handling Empty Collections: If a collection is empty, the output will be an empty array [], which is standard for APIs.
Liquid Filters: The jsonify filter is key here for escaping strings. If it's not available in your setup, ensure you're using a recent version of 11ty and Liquid. You can also use | escape manually, but jsonify is preferred.
Performance and Security: If your collections grow large, the JSON output might become verbose. Consider adding limits in your .eleventy.js config (e.g., slicing the array) if needed. Also, only expose necessary data to avoid leaking sensitive information.
Updates: As before, the JSON files will regenerate on every build, so integrate this into your deployment workflow.
This approach keeps everything in Liquid while achieving the same JSON API output. If you run into any Liquid-specific issues (e.g., filter availability), let me know for further tweaks!