1use crate::extract::Request;
2use crate::extract::{rejection::*, FromRequest};
3use axum_core::extract::OptionalFromRequest;
4use axum_core::response::{IntoResponse, IntoResponseFailed, Response};
5use bytes::Bytes;
6use http::{
7 header::{self, HeaderMap, HeaderValue},
8 StatusCode,
9};
10use serde_core::{de::DeserializeOwned, Serialize};
11
12#[derive(Debug, Clone, Copy, Default)]
95#[cfg_attr(docsrs, doc(cfg(feature = "json")))]
96#[must_use]
97pub struct Json<T>(pub T);
98
99impl<T, S> FromRequest<S> for Json<T>
100where
101 T: DeserializeOwned,
102 S: Send + Sync,
103{
104 type Rejection = JsonRejection;
105
106 async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> {
107 if !json_content_type(req.headers()) {
108 return Err(MissingJsonContentType.into());
109 }
110
111 let bytes = Bytes::from_request(req, state).await?;
112 Self::from_bytes(&bytes)
113 }
114}
115
116impl<T, S> OptionalFromRequest<S> for Json<T>
117where
118 T: DeserializeOwned,
119 S: Send + Sync,
120{
121 type Rejection = JsonRejection;
122
123 async fn from_request(req: Request, state: &S) -> Result<Option<Self>, Self::Rejection> {
124 let headers = req.headers();
125 if headers.get(header::CONTENT_TYPE).is_some() {
126 if json_content_type(headers) {
127 let bytes = Bytes::from_request(req, state).await?;
128 Ok(Some(Self::from_bytes(&bytes)?))
129 } else {
130 Err(MissingJsonContentType.into())
131 }
132 } else {
133 Ok(None)
134 }
135 }
136}
137
138fn json_content_type(headers: &HeaderMap) -> bool {
139 headers
140 .get(header::CONTENT_TYPE)
141 .and_then(|content_type| content_type.to_str().ok())
142 .and_then(|content_type| content_type.parse::<mime::Mime>().ok())
143 .is_some_and(|mime| {
144 mime.type_() == "application"
145 && (mime.subtype() == "json" || mime.suffix().is_some_and(|name| name == "json"))
146 })
147}
148
149axum_core::__impl_deref!(Json);
150
151impl<T> From<T> for Json<T> {
152 fn from(inner: T) -> Self {
153 Self(inner)
154 }
155}
156
157impl<T> Json<T>
158where
159 T: DeserializeOwned,
160{
161 pub fn from_bytes(bytes: &[u8]) -> Result<Self, JsonRejection> {
165 fn make_rejection(err: serde_path_to_error::Error<serde_json::Error>) -> JsonRejection {
167 match err.inner().classify() {
168 serde_json::error::Category::Data => JsonDataError::from_err(err).into(),
169 serde_json::error::Category::Syntax | serde_json::error::Category::Eof => {
170 JsonSyntaxError::from_err(err).into()
171 }
172 serde_json::error::Category::Io => {
173 if cfg!(debug_assertions) {
174 unreachable!()
177 } else {
178 JsonSyntaxError::from_err(err).into()
179 }
180 }
181 }
182 }
183
184 serde_json::from_slice(bytes).map(Self).or_else(|_| {
186 let mut deserializer = serde_json::Deserializer::from_slice(bytes);
187
188 serde_path_to_error::deserialize(&mut deserializer)
189 .map_err(make_rejection)
190 .and_then(|value| {
191 deserializer
192 .end()
193 .map(|()| Self(value))
194 .map_err(|err| JsonSyntaxError::from_err(err).into())
195 })
196 })
197 }
198}
199
200impl<T> IntoResponse for Json<T>
201where
202 T: Serialize,
203{
204 fn into_response(self) -> Response {
205 fn make_response(buf: Vec<u8>, ser_result: serde_json::Result<()>) -> Response {
207 match ser_result {
208 Ok(()) => (
209 [(
210 header::CONTENT_TYPE,
211 HeaderValue::from_static(mime::APPLICATION_JSON.as_ref()),
212 )],
213 buf,
214 )
215 .into_response(),
216 Err(err) => (
217 StatusCode::INTERNAL_SERVER_ERROR,
218 [(
219 header::CONTENT_TYPE,
220 HeaderValue::from_static(mime::TEXT_PLAIN_UTF_8.as_ref()),
221 )],
222 IntoResponseFailed,
223 err.to_string(),
224 )
225 .into_response(),
226 }
227 }
228
229 let mut buf = Vec::with_capacity(128);
232 let res = serde_json::to_writer(&mut buf, &self.0);
233 make_response(buf, res)
234 }
235}
236
237#[cfg(test)]
238mod tests {
239 use super::*;
240 use crate::{routing::post, test_helpers::*, Router};
241 use serde::Deserialize;
242 use serde_json::{json, Value};
243
244 #[crate::test]
245 async fn deserialize_body() {
246 #[derive(Debug, Deserialize)]
247 struct Input {
248 foo: String,
249 }
250
251 let app = Router::new().route("/", post(|input: Json<Input>| async { input.0.foo }));
252
253 let client = TestClient::new(app);
254 let res = client.post("/").json(&json!({ "foo": "bar" })).await;
255 let body = res.text().await;
256
257 assert_eq!(body, "bar");
258 }
259
260 #[crate::test]
261 async fn consume_body_to_json_requires_json_content_type() {
262 #[derive(Debug, Deserialize)]
263 struct Input {
264 foo: String,
265 }
266
267 let app = Router::new().route("/", post(|input: Json<Input>| async { input.0.foo }));
268
269 let client = TestClient::new(app);
270 let res = client.post("/").body(r#"{ "foo": "bar" }"#).await;
271
272 let status = res.status();
273
274 assert_eq!(status, StatusCode::UNSUPPORTED_MEDIA_TYPE);
275 }
276
277 #[crate::test]
278 async fn json_content_types() {
279 async fn valid_json_content_type(content_type: &str) -> bool {
280 println!("testing {content_type:?}");
281
282 let app = Router::new().route("/", post(|Json(_): Json<Value>| async {}));
283
284 let res = TestClient::new(app)
285 .post("/")
286 .header("content-type", content_type)
287 .body("{}")
288 .await;
289
290 res.status() == StatusCode::OK
291 }
292
293 assert!(valid_json_content_type("application/json").await);
294 assert!(valid_json_content_type("application/json; charset=utf-8").await);
295 assert!(valid_json_content_type("application/json;charset=utf-8").await);
296 assert!(valid_json_content_type("application/cloudevents+json").await);
297 assert!(!valid_json_content_type("text/json").await);
298 }
299
300 #[crate::test]
301 async fn invalid_json_syntax() {
302 let app = Router::new().route("/", post(|_: Json<serde_json::Value>| async {}));
303
304 let client = TestClient::new(app);
305 let res = client
306 .post("/")
307 .body("{")
308 .header("content-type", "application/json")
309 .await;
310
311 assert_eq!(res.status(), StatusCode::BAD_REQUEST);
312 }
313
314 #[crate::test]
315 async fn extra_chars_after_valid_json_syntax() {
316 #[derive(Debug, Deserialize)]
317 struct Input {
318 foo: String,
319 }
320
321 let app = Router::new().route("/", post(|input: Json<Input>| async { input.0.foo }));
322
323 let client = TestClient::new(app);
324 let res = client
325 .post("/")
326 .body(r#"{ "foo": "bar" } baz "#)
327 .header("content-type", "application/json")
328 .await;
329
330 assert_eq!(res.status(), StatusCode::BAD_REQUEST);
331 let body_text = res.text().await;
332 assert_eq!(
333 body_text,
334 "Failed to parse the request body as JSON: trailing characters at line 1 column 18"
335 );
336 }
337
338 #[derive(Deserialize)]
339 struct Foo {
340 #[allow(dead_code)]
341 a: i32,
342 #[allow(dead_code)]
343 b: Vec<Bar>,
344 }
345
346 #[derive(Deserialize)]
347 struct Bar {
348 #[allow(dead_code)]
349 x: i32,
350 #[allow(dead_code)]
351 y: i32,
352 }
353
354 #[crate::test]
355 async fn invalid_json_data() {
356 let app = Router::new().route("/", post(|_: Json<Foo>| async {}));
357
358 let client = TestClient::new(app);
359 let res = client
360 .post("/")
361 .body("{\"a\": 1, \"b\": [{\"x\": 2}]}")
362 .header("content-type", "application/json")
363 .await;
364
365 assert_eq!(res.status(), StatusCode::UNPROCESSABLE_ENTITY);
366 let body_text = res.text().await;
367 assert_eq!(
368 body_text,
369 "Failed to deserialize the JSON body into the target type: b[0]: missing field `y` at line 1 column 23"
370 );
371 }
372}