spring_web_dart library
The web vocabulary shared by the Spring Dart server and HTTP client: the annotations that map HTTP calls to methods, and the types that describe requests and responses.
Import it to write a web API or to call one. The same annotations
serve both sides: on a @RestController class (with
spring_boot_starter_web) they say which requests a method answers;
on a @FeignClient interface (with spring_boot_starter_feign) they
say which request calling a method sends. It holds:
- the mapping annotations (
@RequestMapping,@GetMapping,@PostMapping, ...) and the parameter annotations (@PathVariable,@RequestParam,@RequestHeader,@CookieValue,@RequestBody,@RequestPart); - the controller annotations (
@RestController,@ControllerAdvice,@ExceptionHandler,@ResponseStatus,@CrossOrigin); - the HTTP types:
ResponseEntity,HttpHeaders,HttpStatus,HttpMethod,MediaType,ProblemDetailand the errors that carry a response (ResponseStatusException, ...), multipart bodies and uploaded files, path patterns; - the server's request and response (
ServerHttpRequest,ServerHttpResponse), and the origins a server allows (AllowedOrigins, shared by CORS and WebSocket handshakes); - the client transports that send HTTP and WebSocket traffic
(
HttpTransport,WebSocketTransport;platformHttpTransport()picks the right one for the VM, Flutter or the browser); - server-sent events (
EventStream<T>,ServerSentEvent<T>); - the
RequestDeadlinethat limits the total time of a request and the calls it makes (an extension; Spring has no counterpart).
// The server side: GET /books/978-0 answers with the book as JSON.
@RestController()
@RequestMapping('/books')
class BookController {
BookController(this.books);
final BookService books;
@GetMapping('/{isbn}')
Future<Book> find(@PathVariable() String isbn) => books.find(isbn);
}
// The client side: calling find sends that same request.
@FeignClient('catalog', url: r'${catalog.url}')
abstract interface class CatalogClient {
@GetMapping('/books/{isbn}')
Future<Book> find(@PathVariable() String isbn);
}
Platform transports are in package:spring_web_dart/io.dart
(IoHttpTransport, IoWebSocketTransport) and
package:spring_web_dart/browser.dart (FetchHttpTransport,
BrowserWebSocketTransport); test doubles in
package:spring_web_dart/testing.dart (MockHttpTransport,
MockWebSocketTransport, ...).
Spring (Java): spring-web (org.springframework.web.bind.annotation,
org.springframework.http, org.springframework.http.client).
Classes
- AllowedOrigins
-
The browser origins a server takes requests from, checked as Spring's
CorsConfigurationchecks itsallowedOriginsandallowedOriginPatterns. - CloseStatus
- Why a WebSocket connection closed: the numeric code and optional reason text of the close frame (RFC 6455).
- ContentDisposition
-
The value of a
Content-Dispositionheader: whether a body is shown by the browser (inline), saved as a file (attachment) or is one field of a multipart form (form-data), with the file or field name. - ControllerAdvice
-
Marks a bean whose
@ExceptionHandlermethods turn errors into responses for every controller of the application. - CookieValue
- Binds a method parameter to a cookie of the request.
- CrossOrigin
- Lets web pages from other origins call a controller or one of its methods (CORS).
- DeleteMapping
-
Maps HTTP
DELETErequests to a method. On a controller, the method answers them; on a Feign client, calling the method sends one. - ErrorResponse
- An error that carries its own HTTP answer: a status, headers and a ProblemDetail body.
-
EventStream<
T> -
A stream of server-sent events (
text/event-stream) that reads as a plainStream<T>of their data, with the whole events still reachable through events. - ExceptionHandler
- Marks a method that turns an exception into the HTTP response.
- FunctionHttpHandler
- An HttpHandler made from a function, for a handler too small to need a class of its own.
- GetMapping
-
Maps HTTP
GETrequests to a method. On a controller, the method answers them; on a Feign client, calling the method sends one. - HandlerMapping
- Decides which HttpHandler answers a request, or says that the request is not its business.
- HttpHandler
- Something that answers an HTTP request: it reads the request and writes the whole response.
- HttpHeaders
- The headers of an HTTP request or response: name and value pairs where names ignore case and a name may appear several times.
- HttpRequest
- One outgoing HTTP request, complete and ready to send: method, URL, headers, body bytes and timeouts.
- HttpResponse
- A complete HTTP response received by a client: the status code, the headers and the whole body in memory.
- HttpTransport
- The low-level HTTP client: it sends an HttpRequest over the network and gives back the response, without knowing about JSON, annotations or error handling.
- InMemoryMultipartFile
- A MultipartFile whose content is a list of bytes in memory.
- Mapping
-
The interface shared by all request mapping annotations (
@GetMapping,@PostMapping, ...,@RequestMapping): the HTTP method, path, headers and media types of one HTTP call. - MediaType
-
A parsed media type (MIME type), such as
application/jsonortext/plain;charset=UTF-8: the kind of data a body holds. - MediaTypeFactory
-
Guesses the media type of a file from the extension of its name
(
cover.pngisimage/png). - MultipartBody
-
A
multipart/form-databody to send: the parts and the boundary that separates them, encoded into bytes by encode. - MultipartBodyPart
- One part of a multipart body to send: a form field, a file or a JSON value, with its headers.
- MultipartFile
-
A file uploaded with a form (a
multipart/form-datarequest): its name, type, size and content. - MultipartParser
-
Reads a
multipart/form-databody (or anymultipart/*body) part by part, while it arrives. - MultipartPart
- One part of a multipart body, as MultipartParser delivers it while the body is read: its headers and its content as a stream.
- PatchMapping
-
Maps HTTP
PATCHrequests to a method. On a controller, the method answers them; on a Feign client, calling the method sends one. - PathMatch
- A successful PathPattern.match: the values the pattern captured from the path.
- PathPattern
-
A URL path pattern, such as
/books/{isbn}or/static/**, parsed once and then tested against request paths. - PathVariable
-
Binds a method parameter to a
{variable}of the mapping's path. - PostMapping
-
Maps HTTP
POSTrequests to a method. On a controller, the method answers them; on a Feign client, calling the method sends one. - Principal
- The identity of whoever makes a request: a user, a client application or another service, reduced to a name.
- ProblemDetail
-
The body of an error response in the standard JSON form of RFC 9457
(
application/problem+json): a status, a title, a detail message and any extra fields. - PutMapping
-
Maps HTTP
PUTrequests to a method. On a controller, the method answers them; on a Feign client, calling the method sends one. - RequestBody
- Binds a method parameter to the request body.
- RequestContextHolder
- Gives access to the request being handled from code that was not passed it.
- RequestDeadline
- A time limit for the work of one request, carried along with it: code that runs under a deadline (a controller, a service it calls, a Feign client) can ask how much time is left and stop when there is none.
- RequestHeader
- Binds a method parameter to an HTTP header of the request.
- RequestMapping
- Maps HTTP requests of any method to a method, or, on a controller class, gives the base path shared by all its methods.
- RequestParam
-
Binds a method parameter to a query parameter (
?q=dune). - RequestPart
-
Binds a method parameter to one part of a
multipart/form-datarequest: an uploaded file, a text field, or a JSON part. - ResponseCookie
-
A cookie to send to the client, with its attributes (lifetime, scope,
security flags); its toString is the
Set-Cookieheader value. -
ResponseEntity<
T> - An HTTP response as a value: a status code, headers and an optional body.
- ResponseEntityBuilder
- The builder returned by ResponseEntity.status, ResponseEntity.created and the other shortcuts: the status is set, headers are added one by one, and body or build makes the ResponseEntity.
- ResponseStatus
-
Sets the HTTP status of the response of a controller method or an
@ExceptionHandlermethod. - RestController
- Marks a class whose methods answer HTTP requests: a REST controller.
- RestControllerAdvice
- Marks a ControllerAdvice for a REST API, whose handlers write their return value as the response body.
- ServerHttpRequest
- An HTTP request received by the application: method, URL, headers, cookies and a body that can be read once.
- ServerHttpRequestDecorator
- A ServerHttpRequest that forwards every call to another request, so a subclass can change one part of a request and keep the rest.
- ServerHttpResponse
- The HTTP response being written for a request: status code, headers, cookies, then the body.
- ServerHttpResponseDecorator
- A ServerHttpResponse that forwards every call to another response, so a subclass can change one part of the writing and keep the rest.
-
ServerSentEvent<
T> -
One server-sent event, the unit of a
text/event-streamresponse: its data, plus an optional id, event name, retry delay and comment. - SseDecoder
-
A stream transformer that turns the bytes of a
text/event-streambody into ServerSentEvents with text data. - SseReconnect
- The reconnection rules of an event stream: whether, after how long and how many times it connects again when its connection ends or breaks.
- StreamedHttpResponse
- An HTTP response whose status and headers have arrived but whose body is still coming, as a stream of byte chunks.
- WebSocketSession
- One open WebSocket connection: it receives messages as a stream, sends messages, and closes.
- WebSocketTransport
-
The low-level WebSocket client: it opens a connection to a
ws:orwss:URL and hands back the open WebSocketSession.
Enums
- FetchCredentials
-
Whether a browser sends its cookies (and HTTP authentication) with a
request of a
FetchHttpTransport: thecredentialsoption offetch. - HttpMethod
-
The HTTP request methods (
GET,POST, ...), as an enum. - HttpStatusSeries
- The five classes of HTTP status codes, named by their first digit: informational (1xx), successful, redirection, client error and server error (5xx).
Extension Types
- HttpStatus
-
The standard HTTP status codes as named constants (
HttpStatus.ok,HttpStatus.notFound, ...), each with its reason phrase. - HttpStatusCode
- An HTTP status code (any three-digit number, standard or not) with checks for its class: success, client error, server error, ...
Extensions
- ServerHttpRequestBody on ServerHttpRequest
-
Helpers to read the body and the
Content-Typeof a ServerHttpRequest without handling the byte stream yourself. - ServerHttpResponseWriting on ServerHttpResponse
- A shortcut to answer with a complete text response in one call.
Functions
-
connectServerSentEvents(
Future< StreamedHttpResponse> connect(String? lastEventId), {SseReconnect reconnect = const SseReconnect(), void onReconnect(Object? error, Duration delay, int attempt)?}) → Stream<ServerSentEvent< String> > - Reads server-sent events from an HTTP endpoint as one stream that survives lost connections: when a connection ends or breaks, it opens a new one and goes on.
-
parseCookieHeader(
Iterable< String> values) → Map<String, String> -
Reads the cookies of
Cookieheadervalues(a=1; b=2) into a map from name to value. -
platformHttpTransport(
{Duration? connectTimeout, FetchCredentials credentials = FetchCredentials.sameOrigin}) → HttpTransport -
Creates the HTTP transport that suits the platform the code runs on:
an
IoHttpTransportwheredart:ioexists (the VM, Flutter on mobile and desktop), aFetchHttpTransportin the browser. -
platformWebSocketTransport(
{int? maxTextMessageSize, int? maxBinaryMessageSize}) → WebSocketTransport -
Creates the WebSocket transport that suits the platform the code runs
on: an
IoWebSocketTransportwheredart:ioexists (the VM, Flutter on mobile and desktop), aBrowserWebSocketTransportin the browser.
Exceptions / Errors
- ErrorResponseException
- An exception that makes the server answer with a given status, headers and problem body: the base class of the web server's own errors.
- HttpTransportException
-
Thrown by an HttpTransport when a request got no response at all: the
connection could not be opened, it broke, or the request's
timeoutorreadTimeoutran out. In the browser a request blocked by CORS fails this way too. - InvalidMediaTypeException
- The error thrown by MediaType.parse and the MediaType constructor for text that is not a valid media type.
- MultipartException
- Thrown by MultipartParser when a multipart body does not follow the format: no boundary, a part that never ends, headers too large.
- PayloadTooLargeException
- Thrown while reading a request body that is longer than allowed.
- RequestDeadlineExceededException
- Thrown by RequestDeadline.check when the deadline has passed.
- ResponseStatusException
- An exception that makes the server answer with a status code and an optional message.
- WebSocketException
- Thrown when a WebSocket connection cannot be opened or used: the server is unreachable, refuses the handshake, does not answer in time, the connection breaks, or a message is sent on a closed session.