Okay, here's a comprehensive approach to generating JSON APIs for your 11ty website, specifically tailored for your story, post-match, and pre-match collections. This solution leverages 11ty's data cascade and custom template features.
1. Configuration (.eleventy.js)
This configuration sets up the collection definitions (which you already have), and defines a jsonify filter to help output the JSON in a readable way.
const { DateTime } = require("luxon");
module.exports = function(eleventyConfig) {
// 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));
});
// Add a filter to format JSON nicely
eleventyConfig.addFilter("jsonify", function(value) {
return JSON.stringify(value, null, 2); // Use 2 spaces for indentation
});
eleventyConfig.addPassthroughCopy("assets");
eleventyConfig.addPassthroughCopy("admin");
// Format date for display purposes
eleventyConfig.addFilter("postDate", (dateObj) => {
return DateTime.fromJSDate(dateObj).toLocaleString(DateTime.DATE_MED);
});
return {
dir: {
input: "src",
output: "public"
},
templateFormats: ["md", "njk", "html", "liquid"],
markdownTemplateEngine: "liquid",
htmlTemplateEngine: "njk",
dataTemplateEngine: "njk"
};
};
2. Create a Data File (src/_data/metadata.json)
Create a metadata.json file in your src/_data directory (or wherever your global data directory is configured). This allows you to customize the URL's for your API endpoints
{
"apiUrl": "/api"
}
3. Create Template Files for JSON API Endpoints (in src)
Create the following files in your src directory (the location of your 11ty templates):
src/api/stories.json.njk
src/api/post-matches.json.njk
src/api/pre-matches.json.njk
Here's the content of each file. Note that permalink is used to specify the output path and filename. Also note that this can be further customized to only include fields that are useful for your app, and/or change their key names.
src/api/stories.json.njk
---
permalink: "{{ metadata.apiUrl }}/stories.json"
eleventyExcludeFromCollections: true
---
{{ collections.story | jsonify }}
src/api/post-matches.json.njk
---
permalink: "{{ metadata.apiUrl }}/post-matches.json"
eleventyExcludeFromCollections: true
---
{{ collections['post-match'] | jsonify }}
src/api/pre-matches.json.njk
---
permalink: "{{ metadata.apiUrl }}/pre-matches.json"
eleventyExcludeFromCollections: true
---
{{ collections['pre-match'] | jsonify }}
Explanation and Key Improvements:
permalink Frontmatter: This is crucial. It tells 11ty where to write the output file. The permalink value is set to the desired URL structure for each API endpoint based on the apiUrl in metadata.json.
eleventyExcludeFromCollections: true: This line prevents these JSON templates from being included in your other collections (like your regular website pages). This is important to avoid unexpected behavior.
jsonify Filter: The jsonify filter provides a human-readable JSON format in development. Remove it (or change it to JSON.stringify(value)) in production if you want the smallest possible JSON output.
- Accessing Collections:
collections.story, collections['post-match'], and collections['pre-match'] access the collections you defined in .eleventy.js. Note the bracket notation is needed for keys containing a dash, as in post-match.
- Data Cascade: The use of
metadata.apiUrl in the permalink takes advantage of 11ty's data cascade, allowing you to configure the base API URL in a single data file.
How it Works:
- 11ty Processes Templates: 11ty reads the Nunjucks template files (e.g.,
stories.json.njk).
- Accesses Collections: The template code accesses the data from your defined collections.
- Transforms to JSON: The
jsonify filter (or JSON.stringify) converts the data into JSON format.
- Writes to Output: The
permalink frontmatter instructs 11ty to write the generated JSON to the specified files in your output directory (e.g., /public/api/stories.json).
To Access the API Endpoints:
After running npx @11ty/eleventy, you can access the JSON API endpoints at the following URLs (assuming your site is served from the root):
http://localhost:8080/api/stories.json
http://localhost:8080/api/post-matches.json
http://localhost:8080/api/pre-matches.json
Important Considerations:
- Caching: For production, consider implementing caching on your web server (e.g., Cloudflare, Netlify's CDN) to improve performance and reduce load. You can also set appropriate HTTP
Cache-Control headers.
- Error Handling: You might want to add error handling to your API endpoints (e.g., if a collection is empty, return an appropriate error message).
- Security: If your data is sensitive, implement proper authentication and authorization mechanisms. This is beyond the scope of this 11ty code, but needs to be considered.
- Pagination: If your collections become very large, consider adding pagination to your API endpoints to avoid overwhelming the client. This would require more complex template logic and potentially custom JavaScript.
- Content Security Policy (CSP): If you are using a CSP on your website, you may need to adjust it to allow requests to your API endpoints.
- Deployment: Make sure that your deployment process includes the
api directory and its contents.
This approach provides a clean, maintainable way to generate JSON APIs directly from your 11ty website content. Remember to adapt and extend it based on your specific needs and constraints.