HTTP types
The building blocks of requests and responses, shared by the server, the clients and tests: a response with a status and headers (ResponseEntity), headers (HttpHeaders), status codes (HttpStatus), media types (MediaType), the standard error body (ProblemDetail) and multipart files.
Why
A controller, a Feign client and a test all speak about the same things: a 404, a Content-Type, a JSON error body. One set of types, with Spring's names, keeps them interchangeable and familiar.
Example
// Headers of a call to an API that wants a token.
final headers = HttpHeaders()
..contentType = MediaType.applicationJson
..setBearerAuth(token);
headers.forEach((name, values) => log.debug('$name: ${values.join(', ')}'));
// Status codes are ints, so they compare directly.
if (response.statusCode.is2xxSuccessful) { /* ... */ }
if (response.statusCode == HttpStatus.notFound) { /* ... */ }
HttpStatus.valueOf(503).reasonPhrase; // 'Service Unavailable'
// A controller answer with a status and a Location header.
ResponseEntity<Book> created(Book book) =>
ResponseEntity.created(Uri.parse('/api/books/${book.isbn}')).body(book);
// The answer to a request for a book that does not exist.
final problem = ProblemDetail.forStatusAndDetail(HttpStatus.notFound, 'No book 978-0')
..setProperty('isbn', '978-0'); // lets the client show which one
problem.toJson();
// {type: about:blank, title: Not Found, status: 404, detail: No book 978-0, isbn: 978-0}
Responses, headers and statuses
| Type | Spring | What |
|---|---|---|
ResponseEntity<T> |
ResponseEntity<T> |
A status code, headers and a body. ResponseEntity.ok(body), ResponseEntity.created(uri).body(x), ResponseEntity.notFound().build(), ResponseEntity.status(s), accepted(), noContent(), badRequest(), unprocessableContent(), internalServerError(), ResponseEntity.of(nullableBody) (or ofNullable). |
HttpHeaders |
HttpHeaders |
Headers by name, case-insensitive, several values per name, order and casing kept. forEach((name, values)), toSingleValueMap(), toMap(), getAll, operator [] (the first value); typed accessors contentType, accept, eTag, ifNoneMatch, lastModified, date, contentDisposition, location, contentLength; setBearerAuth, setBasicAuth; constants such as HttpHeaders.contentTypeHeader. |
HttpStatus |
HttpStatus |
Every Spring 7 status as an int constant (notFound, unprocessableContent, contentTooLarge...), with reasonPhrase, series, is2xxSuccessful, is4xxClientError, isError; valueOf(404), resolve(599). 100 Continue is HttpStatus.continue_. |
HttpStatusCode |
HttpStatusCode |
Any status code, also one without a constant: HttpStatusCode.valueOf(599).is5xxServerError. A response's statusCode has this type. |
HttpStatusSeries |
HttpStatus.Series |
informational, successful, redirection, clientError, serverError. |
HttpMethod |
HttpMethod |
get, post...; value is the text (GET), parse('POST') reads it (case-sensitive; other text throws). |
MediaType |
MediaType |
Constants as strings (applicationJson, applicationProblemJson...), usable in annotations; MediaType.parse gives an object with includes, isCompatibleWith, charset, qualityValue. |
CacheControl |
CacheControl |
A Cache-Control value: CacheControl.maxAge(d), .noCache(), .noStore(), .empty(), then more directives. |
Errors: ProblemDetail
An API error needs a body a client can read. ProblemDetail is the standard one (RFC 9457, application/problem+json): a status, a short title, a detail text, and any extra fields.
| Type | Spring | What |
|---|---|---|
ProblemDetail |
ProblemDetail |
type (about:blank by default), title (the status's reason phrase by default), status, detail, instance, extra properties. forStatus, forStatusAndDetail, setProperty, toJson, fromJson. |
ErrorResponse |
ErrorResponse |
An exception that knows its answer: statusCode, headers, body (a ProblemDetail). |
ErrorResponseException |
the same | An ErrorResponse to throw or extend: ErrorResponseException(status, body:, headers:, cause:). |
ResponseStatusException |
the same | The shortest way to fail with a status: throw ResponseStatusException(HttpStatus.notFound, 'No book 9'). |
The web server writes a ProblemDetail for its own errors (see ProblemDetail in the web starter).
Multipart and files
Uploads travel as multipart/form-data: one body made of parts, each a form field or a file.
| Type | Spring | What |
|---|---|---|
MultipartFile |
MultipartFile |
An uploaded file: name, originalFilename, contentType, size, isEmpty, headers, bytes, openRead(), transferTo(path). |
InMemoryMultipartFile |
MockMultipartFile (roughly) |
A MultipartFile held in memory, such as a file a client sends (InMemoryMultipartFile.fromString(name, text)). |
MultipartParser |
the parsing of StandardServletMultipartResolver |
Reads a multipart/* body part by part as it arrives: MultipartParser.boundaryOf(contentType), bind(body). |
MultipartBody, MultipartBodyPart |
MultipartBodyBuilder |
Writes a body from MultipartBodyPart.field, .file and .json parts; contentType (with the boundary), encode(). |
MediaTypeFactory |
MediaTypeFactory |
The media type of a file name: MediaTypeFactory.getMediaType('cover.png') is image/png, null when unknown. |
// Upload a book with its cover through a bare transport.
final body = MultipartBody([
MultipartBodyPart.field('title', 'Dune'),
MultipartBodyPart.file('cover', bytes, filename: 'dune.png'), // image/png from the name
]);
await transport.send(HttpRequest(
method: HttpMethod.post,
url: Uri.parse('https://api.neon.books/books'),
headers: HttpHeaders({HttpHeaders.contentTypeHeader: body.contentType}),
body: body.encode(),
));
In Spring (Java)
The names are Spring's, with Dart's shape: HttpStatus constants are ints (no name()), HttpHeaders constants end in Header (the plain names are the typed accessors), MediaType constants are strings, ResponseEntity.of takes a nullable body. The full list is on Differences from Spring.