0Pricing
Learn Rust Coding · Lektion

Extractors

Requests parsen

Extractors ist eine kostenlose Learn Rust Coding-Lektion auf CoddyKit. Dies ist Lektion 2 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des Learn Rust Coding-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der Learn Rust Coding-Kurs umfasst insgesamt 4 Lektionen.

Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.

What is an extractor?

An extractor is a handler parameter that pulls a piece of the request out for you. Axum inspects the parameter types and fills them in.

  • No manual request parsing
  • Type-driven and composable

Path extractor

Path captures dynamic URL segments. The type inside determines how the segment is parsed.

use axum::extract::Path;

async fn user(Path(id): Path<u32>) -> String {
    format!("user {}", id)
}

Multiple path params

Capture several segments by extracting a tuple. Order matches the path pattern.

use axum::extract::Path;

async fn item(Path((cat, id)): Path<(String, u32)>) -> String {
    format!("{} / {}", cat, id)
}

Query extractor

Query deserializes the URL query string into a struct using serde. Great for filters and pagination.

use axum::extract::Query;
use serde::Deserialize;

#[derive(Deserialize)]
struct Page { page: u32 }

async fn list(Query(p): Query<Page>) -> String {
    format!("page {}", p.page)
}

JSON body extractor

Json deserializes a request body into a struct. The struct must derive Deserialize.

use axum::Json;
use serde::Deserialize;

#[derive(Deserialize)]
struct NewUser { name: String }

async fn create(Json(u): Json<NewUser>) -> String {
    format!("created {}", u.name)
}

Headers extractor

Access headers with the HeaderMap extractor or typed header extractors. Useful for auth tokens.

use axum::http::HeaderMap;

async fn show(headers: HeaderMap) -> String {
    match headers.get("x-api-key") {
        Some(v) => format!("key: {:?}", v),
        None => "no key".to_string(),
    }
}

Extractor order matters

Body-consuming extractors like Json must come last in the parameter list, because the body can only be read once.

use axum::{Json, extract::Path};
use serde::Deserialize;

#[derive(Deserialize)]
struct Body { value: i32 }

async fn h(Path(id): Path<u32>, Json(b): Json<Body>) -> String {
    format!("{} {}", id, b.value)
}

Modeling extraction in plain Rust

Extraction is just parsing typed data out of a request. Here we deserialize a query-like string into numbers.

fn parse_query(q: &str) -> Option<u32> {
    q.strip_prefix("page=")?.parse().ok()
}

fn main() {
    println!("{:?}", parse_query("page=3"));
    println!("{:?}", parse_query("bad"));
}

Optional extraction

Wrap an extractor in Option to make it non-fatal. A missing or invalid value yields None instead of an error response.

use axum::extract::Query;
use serde::Deserialize;

#[derive(Deserialize)]
struct Filter { q: String }

async fn search(filter: Option<Query<Filter>>) -> String {
    match filter {
        Some(Query(f)) => f.q,
        None => "no filter".to_string(),
    }
}

Rejections

When an extractor fails it returns a rejection that becomes an HTTP error response. For example, invalid JSON yields a 422 automatically.

use axum::extract::rejection::JsonRejection;
use axum::Json;

async fn create(body: Result<Json<i32>, JsonRejection>) -> String {
    match body {
        Ok(Json(n)) => format!("ok {}", n),
        Err(_) => "bad body".to_string(),
    }
}

Combining extractors

A handler can use many extractors at once. Axum fills each from its part of the request.

use axum::{Json, extract::{Path, Query}};
use serde::Deserialize;

#[derive(Deserialize)]
struct Q { sort: String }
#[derive(Deserialize)]
struct B { name: String }

async fn h(Path(id): Path<u32>, Query(q): Query<Q>, Json(b): Json<B>) -> String {
    format!("{} {} {}", id, q.sort, b.name)
}

Quick Check

Test your understanding of extractors.

Recap

You learned to parse requests with extractors:

  • Path for URL segments, Query for the query string
  • Json for the body (must be last)
  • HeaderMap for headers
  • Option and Result handle failures gracefully

Next: shared state and JSON responses.

Häufig gestellte Fragen

Ist die Lektion „Extractors“ kostenlos?

Ja — der vollständige Text von „Extractors“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des Learn Rust Coding-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der Learn Rust Coding-Kurs umfasst insgesamt 4 Lektionen.

Was lerne ich in „Extractors“?

Requests parsen Du übst Learn Rust Coding mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.

Brauche ich Erfahrung, um Learn Rust Coding zu starten?

Keine Vorkenntnisse erforderlich. Learn Rust Coding auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 2 von 4.

Wie lange dauert die Lektion „Extractors“?

Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.

Kann ich in dieser Learn Rust Coding-Lektion Code schreiben und ausführen?

Ja. Jede Learn Rust Coding-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.

Alle Lektionen in diesem Kurs

  1. Axum-Routing
  2. Extractors
  3. JSON und State
  4. Middleware
← Zurück zu Learn Rust Coding