Skip to content

Conversation

sengho66
Copy link

Provides a simple example on using worker::Fetch to fetch external API in Cloudflare Workers

kflansburg
kflansburg previously approved these changes Feb 28, 2024
@sengho66 sengho66 requested a review from kflansburg August 20, 2025 14:59
Copy link
Collaborator

@guybedford guybedford left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for pointing out this gap in the examples.

#[event(fetch)]
pub async fn main(req: Request, env: Env, _ctx: Context) -> Result<Response> {
Router::new()
.get_async("/pokemon/:name", handle_single)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we call this pokemon_route_handler, get_pokemon or something that makes it clearer the function is the route handler?

@@ -0,0 +1,21 @@
use worker::{event, Context, Env, Fetch, Request, Response, Result, RouteContext, Router, Url};

const ENDPOINT: &str = "https://pokeapi.co/api/v2/pokemon";
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Again, more descriptive would help:

Suggested change
const ENDPOINT: &str = "https://pokeapi.co/api/v2/pokemon";
const POKEMON_API_URL: &str = "https://pokeapi.co/api/v2/pokemon";

Comment on lines +5 to +13
async fn fetch_pokemon(url_string: &str) -> Result<Response> {
// construct a new Url
let url = Url::parse(url_string)?;
Fetch::Url(url).send().await
}

async fn handle_single(_: Request, ctx: RouteContext<()>) -> Result<Response> {
Ok(fetch_pokemon(&format!("{ENDPOINT}/{}", ctx.param("name").unwrap())).await?)
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seems like it would be easier to read and follow as a single function implementation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants