57 function route($uri, $method) {
58 switch ($uri) {
59 case '/api':
60 if ($method === 'POST') {
61 header('Content-Type: application/json');
83 const form = event.target;
84 const formData = new FormData(form);
85 const response = await fetch('/api', {
86 method: 'POST',
87 headers: {
1Serve a REST API in PHP syntax using php-wasm and Val Town.
1// This val creates a simple web interface for opening the Val Town office door.
2// It uses the Hono framework for routing and HTML rendering, and interacts with
3// the SwitchBot API to control the door. The approach includes:
4// 1. A frontend route that displays a button to open the door
5// 2. A backend route that handles the door opening request
6// 3. Integration with SwitchBot API for door control
7// 4. Basic error handling and email notification on failure
8
29 .toString("base64");
30
31 const response = await fetch(`https://api.switch-bot.com/${path}`, {
32 headers: {
33 "Authorization": token,
1// This val creates a movie guessing game using the TMDB API.
2// We'll fetch random movies from different years, present them to the user, and check their guesses.
3// Tradeoffs: We're using a free API with authentication for better data variety.
4
5import { extractValInfo } from "https://esm.town/v/pomdtr/extractValInfo"
6import { blob } from "https://esm.town/v/std/blob"
7
8const TMDB_API_BASE = "https://api.themoviedb.org/3"
9const TMDB_IMAGE_BASE = "https://image.tmdb.org/t/p/w200"
10
11const headers = {
12 Authorization: `Bearer ${Deno.env.get("TMDB_API_KEY")}`,
13}
14
24 chosen.add(year)
25 const response = await fetch(
26 `${TMDB_API_BASE}/discover/movie?language=en-US&sort_by=popularity.desc&include_adult=false&include_video=false&page=1&primary_release_year=${year}`,
27 { headers },
28 )
80 <p><a href="/all-guesses">View All Guesses</a></p>
81 <div class="footer">
82 This product uses the TMDB API but is not endorsed or certified by TMDB.
83 <br>
84 <a href="https://www.themoviedb.org/" target="_blank">
141 <a href="/">Play Again</a> | <a href="/all-guesses">View All Guesses</a>
142 <div class="footer">
143 This product uses the TMDB API but is not endorsed or certified by TMDB.
144 <br>
145 <a href="https://www.themoviedb.org/" target="_blank">
187 <p><a href="/">Back to Quiz</a></p>
188 <div class="footer">
189 This product uses the TMDB API but is not endorsed or certified by TMDB.
190 <br>
191 <a href="https://www.themoviedb.org/" target="_blank">
35 Make an HTTP val (other vals are currently not supported to run, even though we have examples for them).
36 Start your response with a comment explaining how your approach will work, what libraries or
37 API calls you will use, and any tradeoffs you're making. Then write the code in a consise way,
38 the simplest way to achieve the goal, though you can add some inline comments to explain your
39 reasoning (not for every line, but for major groups of lines). Don't use any environment variables
40 unless strictly necessary, for example use APIs that don't require a key, prefer internal function
41 imports (using esm.town), and prefer putting API keys as inline variables. Use built-in Deno
42 functions where possible. Unless specified, don't add error handling,
43 make sure that errors bubble up to the caller.
44 Avoid external images or base64 images, use emojis, unicode symtols, or icon fonts/libraries instead, unless that's
45 not practical for the user's request (e.g. if they ask for a particular animated gif).
46 If the user asks for something that requires persistence, use the Val Town Blob storage API, unless
47 explicitly specified otherwise. Use the current val name for the storage key, which you can get
48 using the "pomdtr/extractValInfo" val, which you can call like this:
422 const tempValName = `valle_tmp_${Math.random() * 10}`.replaceAll(".", "");
423 const newCode = tokens.join("").replaceAll("```ts", "").replaceAll("```", "").replace(/^ts\n/, "");
424 // Errors in running the val bubble up through this API, so ignore them.
425 await vt.vals.create({ name: tempValName, code: newCode, type: "httpnext" as any, privacy: "unlisted" }).catch(
426 (error) => {
35 Make an HTTP val (other vals are currently not supported to run, even though we have examples for them).
36 Start your response with a comment explaining how your approach will work, what libraries or
37 API calls you will use, and any tradeoffs you're making. Then write the code in a consise way,
38 the simplest way to achieve the goal, though you can add some inline comments to explain your
39 reasoning (not for every line, but for major groups of lines). Don't use any environment variables
40 unless strictly necessary, for example use APIs that don't require a key, prefer internal function
41 imports (using esm.town), and prefer putting API keys as inline variables. Use built-in Deno
42 functions where possible. Unless specified, don't add error handling,
43 make sure that errors bubble up to the caller.
44 Avoid external images or base64 images, use emojis, unicode symtols, or icon fonts/libraries instead, unless that's
45 not practical for the user's request (e.g. if they ask for a particular animated gif).
46 If the user asks for something that requires persistence, use the Val Town Blob storage API, unless
47 explicitly specified otherwise. Use the current val name for the storage key, which you can get
48 using the "pomdtr/extractValInfo" val, which you can call like this:
422 const tempValName = `valle-tmp-${Math.random() * 10}`.replaceAll(".", "");
423 const newCode = tokens.join("").replaceAll("```ts", "").replaceAll("```", "").replace(/^ts\n/, "");
424 // Errors in running the val bubble up through this API, so ignore them.
425 await vt.vals.create({ name: tempValName, code: newCode, type: "httpnext" as any, privacy: "unlisted" }).catch(
426 (error) => {
6* Fork this val to your own profile.
7* Make a folder for the temporary vals that get generated, take the ID from the URL, and put it in `tempValsParentFolderId`.
8* If you want to use OpenAI models you need to set the `OPENAI_API_KEY` [env var](https://www.val.town/settings/environment-variables).
9* If you want to use Anthropic models you need to set the `ANTHROPIC_API_KEY` [env var](https://www.val.town/settings/environment-variables).
10* Create a [Val Town API token](https://www.val.town/settings/api), open the browser preview of this val, and use the API token as the password to log in.
11
12<img width=500 src="https://imagedelivery.net/iHX6Ovru0O7AjmyT5yZRoA/7077d1b5-1fa7-4a9b-4b93-f8d01d3e4f00/public"/>
36
37Custom middleware can be added in an array as the third argument.
38Middleware can add data to the `req.data` object or return a response for things like API endpoints.
39
40```tsx
62```tsx
63// example middleware
64async function api (req: Request, res: Response, next): Promise<Response> {
65 if (req.pathname !== "/api") return next();
66 if (req.method === "POST") {
67 return Repsonse.json({ message: "Hello POST request" });
70}
71
72export default render(App, import.meta.url, [ api ]);
73```
74
11- [ ] Have any other email login ping me for approval or make a private val with a list of approved emails
12
13## Switchbot API
14
15This val authenticates to the switchbot API with `SWITCHBOT_TOKEN` and `SWITCHBOT_KEY`.
16
17Learn how to get your own Switchbot API keys here: [Switchbot Docs](https://github.com/OpenWonderLabs/SwitchBotAPI).
18
19Migrated from folder: Archive/switchbot
2 const readmeVals: any = await (await fetch("https://janpaul123-readmevals.web.val.run/")).json();
3
4 const API_URL = "https://api.val.town";
5
6 const sections = [
118 {
119 prompt: "Write a val that accesses environment variables",
120 code: `const res = await fetch("${API_URL}/v1/me", {
121 headers: {
122 Authorization: \`Bearer \${Deno.env.get("valtown")}\`,
130 code: `import process from "node:process";
131
132 const res = await fetch("${API_URL}/v1/me", {
133 headers: {
134 Authorization: \`Bearer \${process.env.valtown}\`,
299 You can attach files to your emails by using the \`attachments\` field.
300 Attachments need to be [Base64](https://en.wikipedia.org/wiki/Base64) encoded,
301 which is that the [btoa](https://developer.mozilla.org/en-US/docs/Web/API/btoa)
302 method is doing in this example:
303
401 \`\`\`
402
403 ### Lower-level API
404
405 We do provide access to the lower-level getter and setters, which are useful if you are storing non-JSON or binary data, need to stream in your response or request data, or do anything else lower-level.
406
407 - \`async get(key: string)\`: Retrieves a blob for a given key.
408 - \`async set(key: string, value: string | BodyInit)\`: Sets the blob value for a given key. See [BodyInit](https://deno.land/api@v1.38.1?s=BodyInit).
409
410 ### Limitations
533 role: "assistant",
534 content:
535 "```ts\nexport default async function(req: Request): Promise<Response> {\n const apiKey = Deno.env.get(\"METEO_KEY\");\n const apiUrl = `https://api.open-meteo.com/v1/forecast?latitude=40.6782&longitude=-73.9442&hourly=temperature_2m¤t_weather=true&apikey=${apiKey}`;\n\n const response = await fetch(apiUrl);\n const weatherData = await response.json();\n\n return new Response(JSON.stringify(weatherData), { headers: { \"Content-Type\": \"application/json\" } });\n}\n```",
536 },
537 {