http_status 3.3.3

SDKdartflutter
Platformandroidioswindowslinuxmacosweb

Constants enumerating the HTTP status codes in Dart. All status codes defined in RFC1945 (HTTP/1.0, RFC2616 (HTTP/1.1), and RFC2518 (WebDAV) are supported.

http_status

Pub Package build status Coverage Status Star this Repo License: BSD

Constants enumerating the HTTP status codes in Dart. All status codes defined in RFC1945 (HTTP/1.0, RFC2616 (HTTP/1.1), and RFC2518 (WebDAV) are supported.

Codes of Http Status

CodeHttp Status NameHttp Status (v1.x - v2.x Deprecated)Http Status (v2.x - v3.x)
100ContinueContinue / CONTINUEcontinue_
101Switching ProtocolsSwitching_Protocols / SWITCHING_PROTOCOLSswitchingProtocols
102ProcessingProcessing / PROCESSINGprocessing
103Early Hints-earlyHints
200OKOk / OKok
201CreatedCreated / CREATEDcreated
202AcceptedAccepted / ACCEPTEDaccepted
203Non Authoritative InformationNonAuthoritative_Information / NON_AUTHORITATIVE_INFORMATIONnonAuthoritativeInformation
204No ContentNo_Content / NO_CONTENTnoContent
205Reset ContentReset_Content / RESET_CONTENTresetContent
206Partial ContentPartial_Content / PARTIAL_CONTENTpartialContent
207Multi-StatusMultiStatus / MULTISTATUSmultiStatus
208Already ReportedAlready_Reported / ALREADY_REPORTEDalreadyReported
226I'M UsedIM_Used / IM_USEDimUsed
300Multiple ChoicesMultiple_Choices / MULTIPLE_CHOICESmultipleChoices
301Moved PermanentlyMoved_Permanently / MOVED_PERMANENTLYmovedPermanently
302Found / Moved TemporarilyFound / Moved_Temporarily / FOUND / MOVED_TEMPORARILYfound / movedTemporarily
303See OtherSee_Other / SEE_OTHERseeOther
304Not ModifiedNot_Modified / NOT_MODIFIEDnotModified
305Use ProxyUse_Proxy / USE_PROXYuseProxy
307Temporary RedirectTemporary_Redirect / TEMPORARY_REDIRECTtemporaryRedirect
308Permanent RedirectPermanent_Redirect / PERMANENT_REDIRECTpermanentRedirect
400Bad RequestBad_Request / BAD_REQUESTbadRequest
401UnauthorizedUnauthorized / UNAUTHORIZEDunauthorized
402Payment RequiredPayment_Required / PAYMENT_REQUIREDpaymentRequired
403ForbiddenForbidden / FORBIDDENforbidden
404Not FoundNot_Found / NOT_FOUNDnotFound
405Method Not AllowedMethod_Not_Allowed / METHOD_NOT_ALLOWEDmethodNotAllowed
406Not AcceptableNot_Acceptable / NOT_ACCEPTABLEnotAcceptable
407Proxy Authentication RequiredProxy_Authentication_Required / PROXY_AUTHENTICATION_REQUIREDproxyAuthenticationRequired
408Request TimeoutRequest_Timeout / REQUEST_TIMEOUTrequestTimeout
409ConflictConflict / CONFLICTconflict
410GoneGone / GONEgone
411Length RequiredLength_Required / LENGTH_REQUIREDlengthRequired
412Precondition FailedPrecondition_Failed / PRECONDITION_FAILEDpreconditionFailed
413Request Entity Too LargePayload_Too_Large / PAYLOAD_TOO_LARGE / Request_Entity_Too_Large / REQUEST_ENTITY_TOO_LARGErequestEntityTooLarge
414Request-URI Too LongRequestURI_Too_Long / REQUESTURI_TOO_LONG / Request_Uri_Too_Long / REQUEST_URI_TOO_LONGrequestUriTooLong
415Unsupported Media TypeUnsupported_Media_Type / UNSUPPORTED_MEDIA_TYPEunsupportedMediaType
416Requested Range Not SatisfiableRequested_Range_Not_Satisfiable / REQUESTED_RANGE_NOT_SATISFIABLErequestedRangeNotSatisfiable
417Expectation FailedExpectation_Failed / EXPECTATION_FAILEDexpectationFailed
418I'm a teapot-imATeapot
419Insufficient Space on Resource-insufficientSpaceOnResource
420Method Failure-methodFailure
421Misdirected RequestMisdirected_Request / MISDIRECTED_REQUESTmisdirectedRequest
422Unprocessable EntityUnprocessable_Entity / UNPROCESSABLE_ENTITYunprocessableEntity
423LockedLocked / LOCKEDlocked
424Failed DependencyFailed_Dependency / FAILED_DEPENDENCYfailedDependency
426Upgrade RequiredUpgrade_Required / UPGRADE_REQUIREDupgradeRequired
428Precondition RequiredPrecondition_Required / PRECONDITION_REQUIREDpreconditionRequired
429Too Many RequestsToo_Many_Requests / TOO_MANY_REQUESTStooManyRequests
431Request Header Fields Too LargeRequest_Header_Fields_Too_Large / REQUEST_HEADER_FIELDS_TOO_LARGErequestHeaderFieldsTooLarge
444Connection Closed Without ResponseConnection_Closed_Without_Response / CONNECTION_CLOSED_WITHOUT_RESPONSEconnectionClosedWithoutResponse
451Unavailable For Legal ReasonsUnavailable_For_Legal_Reasons / UNAVAILABLE_FOR_LEGAL_REASONSunavailableForLegalReasons
499Client Closed RequestClient_Closed_Request / CLIENT_CLOSED_REQUESTclientClosedRequest
500Internal Server ErrorInternal_Server_Error / INTERNAL_SERVER_ERRORinternalServerError
501Not ImplementedNot_Implemented / NOT_IMPLEMENTEDnotImplemented
502Bad GatewayBad_Gateway / BAD_GATEWAYbadGateway
503Service UnavailableService_Unavailable / SERVICE_UNAVAILABLEserviceUnavailable
504Gateway TimeoutGateway_Timeout / GATEWAY_TIMEOUTgatewayTimeout
505HTTP Version Not SupportedHTTP_Version_Not_Supported / HTTP_VERSION_NOT_SUPPORTEDhttpVersionNotSupported
506Variant Also NegotiatesVariant_Also_Negotiates / VARIANT_ALSO_NEGOTIATESvariantAlsoNegotiates
507Insufficient StorageInsufficient_Storage / INSUFFICIENT_STORAGEinsufficientStorage
508Loop DetectedLoop_Detected / LOOP_DETECTEDloopDetected
510Not ExtendedNot_Extended / NOT_EXTENDEDnotExtended
511Network Authentication RequiredNetwork_Authentication_Required / NETWORK_AUTHENTICATION_REQUIREDnetworkAuthenticationRequired
599Network Connect Timeout ErrorNetwork_Connect_Timeout_Error / NETWORK_CONNECT_TIMEOUT_ERRORnetworkConnectTimeoutError

A library for debugging and displaying http status codes. Includes 63 status codes, messages and desciptions sourced from the official spec https://tools.ietf.org/html/rfc723 and https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/

Installation

dart pub add http_status
# or
flutter pub add http_status

Or in the dependencies: section of your pubspec.yaml, add the following line:

dependencies:
  http_status: <latest_version>

Usage

A simple usage example:

import 'package:http_status/http_status.dart';

main() {
  print('${HttpStatusCode.ok}');
  // 200

  print('${HttpStatus.ok}');
  // HttpStatus(
  //   code: 200,
  //   name: 'OK',
  //   description: 'The request was fulfilled.'
  // )

  print('${HttpStatusCode.noContent}');
  // 204

  print('${HttpStatus.fromCode(404)}');
  // HttpStatus(
  //   code: 404,
  //   name: 'Not Found',
  //   description: 'The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.'
  // )

  // isInformation (Http Status Code 200 - 299)
  print(HttpStatusCode.processing.isInformationHttpStatusCode); // true
  print(HttpStatusCode.notFound.isInformationHttpStatusCode); // false
  print(HttpStatus.fromCode(103).isInformationHttpStatusCode); // true
  print(HttpStatus.fromCode(404).isInformationHttpStatusCode); // false
  print(103.isInformationHttpStatusCode); // true
  print(400.isInformationHttpStatusCode); // false

  // isSuccessful (Http Status Code 200 - 299)
  print(HttpStatusCode.accepted.isSuccessfulHttpStatusCode); // true
  print(HttpStatusCode.notFound.isSuccessfulHttpStatusCode); // false
  print(HttpStatus.fromCode(200).isSuccessfulHttpStatusCode); // true
  print(HttpStatus.fromCode(404).isSuccessfulHttpStatusCode); // false
  print(200.isSuccessfulHttpStatusCode); // true
  print(400.isSuccessfulHttpStatusCode); // false

  // isRedirect (Http Status Code 300 - 399)
  print(HttpStatusCode.permanentRedirect.isRedirectHttpStatusCode); // true
  print(HttpStatusCode.notFound.isRedirectHttpStatusCode); // false
  print(HttpStatus.fromCode(303).isRedirectHttpStatusCode); // true
  print(HttpStatus.fromCode(404).isRedirectHttpStatusCode); // false
  print(303.isRedirectHttpStatusCode); // true
  print(400.isRedirectHttpStatusCode); // false

  // isClientError (Http Status Code 400 - 499)
  print(HttpStatusCode.notFound.isClientErrorHttpStatusCode); // true
  print(HttpStatusCode.processing.isClientErrorHttpStatusCode); // false
  print(HttpStatus.fromCode(404).isClientErrorHttpStatusCode); // true
  print(HttpStatus.fromCode(500).isClientErrorHttpStatusCode); // false
  print(404.isClientErrorHttpStatusCode); // true
  print(200.isClientErrorHttpStatusCode); // false

  // isServerError (Http Status Code 500 - 599)
  print(HttpStatusCode.internalServerError.isServerErrorHttpStatusCode); // true
  print(HttpStatusCode.notFound.isServerErrorHttpStatusCode); // false;
  print(HttpStatus.fromCode(502).isServerErrorHttpStatusCode); // true
  print(HttpStatus.fromCode(200).isServerErrorHttpStatusCode); // false
  print(503.isServerErrorHttpStatusCode); // true
  print(200.isServerErrorHttpStatusCode); // false
}
  1. Classic method

    import 'package:http/http.dart' as http;
    import 'package:http_status/http_status.dart';
    
    final res = await http.get(Uri.parse(url));
    
    if (res.statusCode == HttpStatusCode.ok) { // res.statusCode == 200
      final httpStatus = HttpStatus.fromCode(res.statusCode);
    
      return {
        'statusCode': res.statusCode,
        'httpStatus': httpStatus,
        'data': res.body
      };
    }
    
  2. Alternative method (Same as #1 method, but with more direct validation using .isSuccessfulHttpStatusCode)

    import 'package:http/http.dart' as http;
    import 'package:http_status/http_status.dart';
    
    final res = await http.get(Uri.parse(url));
    
    if (res.statusCode.isSuccessfulHttpStatusCode) {
      final httpStatus = HttpStatus.fromCode(res.statusCode);
    
      return {
        'statusCode': res.statusCode,
        'httpStatus': httpStatus,
        'data': res.body
      };
    }
    
  3. Alternative method (Same as #1 method, if you need the HttpStatus object from the dynamically generated status code of the response)

    import 'package:http/http.dart' as http;
    import 'package:http_status/http_status.dart';
    
    final res = await http.get(Uri.parse(url));
    
    final httpStatusResponse = HttpStatus.fromCode(res.statusCode);
    
    if (httpStatusResponse.isSuccessfulHttpStatusCode) {
      return {
        'statusCode': res.statusCode,
        'httpStatus': httpStatusResponse,
        'data': res.body
      };
    } else if (httpStatusResponse.isClientErrorHttpStatusCode) {
       // Handle client error
       // ...
    } else {
       // Handle other code error
       // ...
    }
    

Thanking all Awesome Contributors :heart:

Contributors

Contributions of any kind are welcome!

License

BSD

Features and bugs

Please file feature requests and bugs at the issue tracker.