Next | Previous

http_curl

IMPORTANT NOTICE:

THIS MODULE WAS FORMERLY THE http module.

THIS MODULE IS DEPRECIATED AND WILL BE REMOVED FROM THE CORE LIBRARY AS SOON AS THE CLIENT OF THE PURE BLADE IMPLEMENTATION IS STABLE.

IT IS ONLY HERE FOR HISTORICAL REASONS AND TO SERVE AS A BASE BENCHMARK FOR THE DEVELOPMENT OF THE http MODULE.

YOU SHOULD USE THE http MODULE INSTEAD AS ITS MORE SUPPORTED, AND ALL FURTHER DEVELOPMENTS TOWARDS HTTP WILL BE DONE THERE.

BUG REPORTS AND ISSUES FOR THIS MODULE WILL NOT BE TREATED AS PRIORITY. The http_curl module provides a rich library to help in building HTTP clients and servers. The module also provides a few generic abstractions for simple HTTP operations such as a GET request.

Examples

The example below shows making a GET request to fetch a webpage.

import http_curl
echo http_curl.get('http://example.com')
# <class HttpResponse instance at 0x600002adacd0>

There is a post() and put() alternative to the get() method called above and they are documented below. For a more controlled HTTP request, you should use the HttpClient class. Below is an example of such implementation that sets the timeout for receiving response back from the server to 30 seconds.

import http_curl
var client = http_curl.HttpClient()
client.receive_timeout = 30000 # Optional
var res = client.send_request('http://example.com/endpoint?query=1', 'GET')
echo res.body.to_string()

Creating a server with the http_curl module is also a breeze. The example below shows an implementation of an HTTP API server listening on port 3000 and simple returns the JSON of the request object itself.

import http_curl
import json
var server = http_curl.server(3000)
server.handle('GET', '/', @(request, response) {
  response.json(request)
})
server.listen()

The http_curl module does not make any assumption as to the type of data to be sent in request bodies and for this reason, it should not be expected to automatically convert dictionaries into JSON objects or create multipart/form-data request for you. Rather, it gives the tools required to craft any request body of your choice.

Fields

http_curl.CONTINUEreadonly int
100 continue.
http_curl.SWITCHING_PROTOCOLSreadonly int
101 switching protocols.
http_curl.PROCESSINGreadonly int
102 processing.
http_curl.OKreadonly int
200 ok.
http_curl.CREATEDreadonly int
201 created.
http_curl.ACCEPTEDreadonly int
202 accepted.
http_curl.NON_AUTHORITATIVE_INFORMATIONreadonly int
203 non authoritative information.
http_curl.NO_CONTENTreadonly int
204 no content.
http_curl.RESET_CONTENTreadonly int
205 reset content.
http_curl.PARTIAL_CONTENTreadonly int
206 partial content.
http_curl.MULTI_STATUSreadonly int
207 multi status.
http_curl.ALREADY_REPORTEDreadonly int
208 already reported.
http_curl.IM_USEDreadonly int
226 im used.
http_curl.MULTIPLE_CHOICESreadonly int
300 multiple choices.
http_curl.MOVED_PERMANENTLYreadonly int
301 moved permanently.
http_curl.FOUNDreadonly int
302 found.
http_curl.SEE_OTHERreadonly int
303 see other.
http_curl.NOT_MODIFIEDreadonly int
304 not modified.
http_curl.USE_PROXYreadonly int
305 use proxy.
http_curl.TEMPORARY_REDIRECTreadonly int
307 temporary redirect.
http_curl.PERMANENT_REDIRECTreadonly int
308 permanent redirect.
http_curl.BAD_REQUESTreadonly int
400 bad request.
http_curl.UNAUTHORIZEDreadonly int
401 unauthorized.
http_curl.PAYMENT_REQUIREDreadonly int
402 payment required.
http_curl.FORBIDDENreadonly int
403 forbidden.
http_curl.NOT_FOUNDreadonly int
404 not found.
http_curl.METHOD_NOT_ALLOWEDreadonly int
405 method not allowed.
http_curl.NOT_ACCEPTABLEreadonly int
406 not acceptable.
http_curl.PROXY_AUTHENTICATION_REQUIREDreadonly int
407 proxy authentication required.
http_curl.REQUEST_TIMEOUTreadonly int
408 request timeout.
http_curl.CONFLICTreadonly int
409 conflict.
http_curl.GONEreadonly int
410 gone.
http_curl.LENGTH_REQUIREDreadonly int
411 length required.
http_curl.PRECONDITION_FAILEDreadonly int
412 precondition failed.
http_curl.PAYLOAD_TOO_LARGEreadonly int
413 payload too large.
http_curl.REQUEST_URI_TOO_LONGreadonly int
414 request uri too long.
http_curl.UNSUPPORTED_MEDIA_TYPEreadonly int
415 unsupported media type.
http_curl.REQUESTED_RANGE_NOT_SATISFIABLEreadonly int
416 requested range not satisfiable.
http_curl.EXPECTATION_FAILEDreadonly int
417 expectation failed.
http_curl.TEAPOTreadonly int
418 teapot.
http_curl.MISDIRECTED_REQUESTreadonly int
421 misdirected request.
http_curl.UNPROCESSABLE_ENTITYreadonly int
422 unprocessable entity.
http_curl.LOCKEDreadonly int
423 locked.
http_curl.FAILED_DEPENDENCYreadonly int
424 failed dependency.
http_curl.UPGRADE_REQUIREDreadonly int
426 upgrade required.
http_curl.PRECONDITION_REQUIREDreadonly int
428 precondition required.
http_curl.TOO_MANY_REQUESTSreadonly int
429 too many requests.
http_curl.REQUEST_HEADER_FIELDS_TOO_LARGEreadonly int
431 request header fields too large.
http_curl.CONNECTION_CLOSED_WITHOUT_RESPONSEreadonly int
444 connection closed without response.
451 unavailable for legal reasons.
http_curl.CLIENT_CLOSED_REQUESTreadonly int
499 client closed request.
http_curl.INTERNAL_SERVER_ERRORreadonly int
500 internal server error.
http_curl.NOT_IMPLEMENTEDreadonly int
501 not implemented.
http_curl.BAD_GATEWAYreadonly int
502 bad gateway.
http_curl.SERVICE_UNAVAILABLEreadonly int
503 service unavailable.
http_curl.GATEWAY_TIMEOUTreadonly int
504 gateway timeout.
http_curl.HTTP_VERSION_NOT_SUPPORTEDreadonly int
505 http version not supported.
http_curl.VARIANT_ALSO_NEGOTIATESreadonly int
506 variant also negotiates.
http_curl.INSUFFICIENT_STORAGEreadonly int
507 insufficient storage.
http_curl.LOOP_DETECTEDreadonly int
508 loop detected.
http_curl.NOT_EXTENDEDreadonly int
510 not extended.
http_curl.NETWORK_AUTHENTICATION_REQUIREDreadonly int
511 network authentication required.
http_curl.NETWORK_CONNECT_TIMEOUT_ERRORreadonly int
599 network connect timeout error.
http_curl.mapreadonly dictionary
A map of status code to their string representation..

Functions

http_curl.set_headers(headers)

Sets the request headers for the current module instance.

This function returns HttpClient in order to allow for idiomatic chaining such as:

import http_curl
echo http_curl.set_headers({
  'Authorization': 'Bearer SomeAPIBearerToken',
  'Host': 'example.com',
}).get('http://example.com/current-user').body.to_string()
  • @params:
    • dict headers
  • @returns: HttpClient
  • @raises:
    • Exception
http_curl.get(url)

Sends an Http GET request and returns an HttpResponse or throws one of SocketException or Exception if it fails.

  • @params:
    • string url
  • @returns: HttpResponse
  • @raises:
    • Exception
    • SocketException
    • HttpException
http_curl.post(url, data)

Sends an Http POST request and returns an HttpResponse.

  • @params:
    • string url
    • string|bytes|nil data
  • @returns: HttpResponse
  • @raises:
    • Exception
    • SocketException
    • HttpException
http_curl.put(url, data)

Sends an Http PUT request and returns an HttpResponse.

  • @params:
    • string url
    • string|bytes|nil data
  • @returns: HttpResponse
  • @raises:
    • Exception
    • SocketException
    • HttpException
http_curl.delete(url)

Sends an Http DELETE request and returns an HttpResponse.

  • @params:
    • string url
  • @returns: HttpResponse
  • @raises:
    • Exception
    • SocketException
    • HttpException
http_curl.server(port, address)

Creates an new HttpServer instance.

  • @params:
    • int port
    • string address
  • @returns: HttpServer
  • @raises:
    • Exception
    • SocketException
    • HttpException
http_curl.client()

Returns the default client.

  • @returns: HttpClient

Classes

class HttpRequest

Http request handler and object.

@printable, @serializable

.request_uristring

The original request URL as sent in the raw request.

.pathstring

The requested path or file. E.g. if the Request URI is /users?sort=desc, then the path is /users.

.methodstring

The HTTP method of the request: GET (the default), POST, PUT, etc.

.hoststring

The hostname derived from the Host header or the first instance of X-Forwarded-Host if set.

.ipstring

The IP address of the remote client that initiated the request.

.ipv6string

The IPv6 address of the remote client that initiated the request.

.headersdictionary

A dictionary containing the headers sent with the request.

.queriesdictionary

A dictionary containing the entries of the URI query string.

.cookiesdictionary

A dictionary containing the cookies sent with the request.

.bodydictionary

A dictionary containing all data submitted in the request body.

.filesdictionary

A dictionary containing the data of all files uploaded in the request.

.http_versionstring

The HTTP version used for the request.

.auth_methodAuth

The HTTP authentication method to use when the uri contains a credential. Default value is Auth.ANY.

.parse(raw_data, client)

Parses a raw HTTP request string into a correct HttpRequest.

  • @params:
    • string raw_data
    • Socket|TLSSocket|nil client
  • @returns: boolean
.send(uri, method, data, options)

Sends the given request to the given uri using the given method and optionally passing the data if given.

  • @params:
    • Url uri
    • string method
    • string|bytes|nil data
    • dict? options
  • @returns: HttpResponse
  • @raises:
    • HttpException
.to_dict()

Returns a dictionary representation of the HttpRequest instance.

  • @returns: dict
.to_string()

Returns a string representation of the HttpRequest instance.

  • @returns: string
class HttpException < Exception

HTTP related Exceptions.

@printable

class HttpServer

HTTP server.

@printable

.hoststring

The host address to which this server will be bound. Default value is socket.IP_LOCAL (127.0.0.1)

.portnumber

The port to which this server will be bound to on the host.

.socket{Socket

The working Socket instance for the HttpServer.

.reuse_addressbool

A boolean value indicating whether to reuse socket addresses or not. Default value is true.

.read_timeoutnumber

The timeout in milliseconds after which an attempt to read clients request data will be terminated. Default value is 2,000 (2 seconds).

.write_timeoutnumber

The timeout in milliseconds after which an attempt to write response data to clients will be terminated.

If we cannot send response to a client after the stipulated time, it will be assumed such clients have disconnected and existing connections for that client will be closed and their respective sockets will be discarded. Default value is 2,000 (2 seconds).

.HttpServer(port, host) ➝ Constructor

http_curl.HttpServer constructor

  • @params:
    • int port
    • string? host
.close()

Stops the server.

.on_connect(function)

Adds a function to be called when a new client connects.

@notes:

  • Function function MUST accept at one parameter which will be passed the client Socket object.
  • Multiple on_connect() may be set on a single instance.
  • @params:
    • function(1) function
.on_disconnect(function)

Adds a function to be called when a new client disconnects.

@notes:

  • Function function MUST accept at one parameter which will be passed the client information.
  • Multiple on_disconnect() may be set on a single instance.
  • @params:
    • function(1) function
.on_receive(handler)

Adds a function to be called when the server receives a message from a client.

Function fn MUST accept TWO parameters. First parameter will accept the HttpRequest object and the second will accept the HttpResponse object.

@notes:

  • Multiple on_receive() may be set on a single instance.
  • @params:
    • function(2) handler
.on_reply(function)

Adds a function to be called when the server sends a reply to a client.

Function function MUST accept one parameter which will be passed the HttpResponse object.

@notes:

  • Multiple on_sent() may be set on a single instance.
  • @params:
    • function(1) function
.on_error(function)

Adds a function to be called when the server encounters an error with a client.

Function function MUST accept two parameters. The first argument will be passed the Exception object and the second will be passed the client Socket object.

@notes:

  • Multiple on_error() may be set on a single instance.
  • @params:
    • function(2) function
.handle(method, path, handler)

Sets up a request handler that will be called when a request with the given method has a path that matches the one specified.

  • @params:
    • string method
    • string path
    • function(2) handler
.none_handler(handler)

Sets up the handle to invoke when a request is not processed. That is, when it does not match a registered route and no on_receive() handler is set.

  • @params:
    • function(2) handler
.listen()

Binds to the instance port and host and starts listening for incoming connection from HTTP clients.

class HttpClient

Handles http requests.

@note This client do not currently support the compress, deflate and gzip transfer encoding.

.user_agentstring

The user agent of the client used to make the request. Default value — Blade HTTP Client/1.0.

.follow_redirectbool

Indicates if we receive a redirect from a server, this flag tells us whether we should follow it or not. Default value is true.

.skip_hostname_verificationbool

Indicates if the site you're connecting to uses a different host name that what they have mentioned in their server certificate's commonName (or subjectAltName) fields, connection will fail. You can skip this check by setting to true, but this will make the connection less secure.

.skip_peer_verificationbool

Indicates if you want to connect to a site who isn't using a certificate that is signed by one of the certs in the CA bundle you have, you can skip the verification of the server's certificate. This makes the connection A LOT LESS SECURE.

.refererstring

The site that refers us to the current site

.ca_certstring

If you have a CA cert for the server stored someplace else than in the default bundle.

.connect_timeoutnumber

The connect timeout duration in milliseconds. Default value is 60,000 (1 minute).

.receive_timeoutnumber

The receive timeout duration in milliseconds. Default value is 300,000 (5 minutes).

.headersdict

A dictionary of headers sent along with the request.

.no_expectbool

Indicates whether to remove the expect header or not only applies to requests with files in the body

.send_request(uri, method, data)

Sends an Http request and returns a HttpResponse.

  • @params:
    • string uri

    • string? method Default value is GET.

    • string|dict|nil data

  • @returns: HttpResponse
  • @raises:
    • SocketException
    • Exception
.get(url)

Sends an Http GET request and returns an HttpResponse.

  • @params:
    • string url
  • @returns: HttpResponse
  • @raises:
    • Exception
    • SocketException
    • HttpException
.post(url, data)

Sends an Http POST request and returns an HttpResponse.

  • @params:
    • string url
    • string|bytes|nil data
  • @returns: HttpResponse
  • @raises:
    • Exception
    • SocketException
    • HttpException
.put(url, data)

Sends an Http PUT request and returns an HttpResponse.

  • @params:
    • string url
    • string|bytes|nil data
  • @returns: HttpResponse
  • @raises:
    • Exception
    • SocketException
    • HttpException
.delete(url)

Sends an Http DELETE request and returns an HttpResponse.

  • @params:
    • string url
  • @returns: HttpResponse
  • @raises:
    • Exception
    • SocketException
    • HttpException
class HttpResponse

Represents the response to an Http request.

@printable, @serializable

.versionstring

The HTTP version of the response

.statusnumber

The HTTP response status code

.headersdictionary

The HTTP response headers

.time_takennumber

Total time taken for the HTTP request that generated this HttpResponse to complete

.redirectsnumber

The number of times the HTTP request that generated this HttpResponse was redirected.

.responderstring

The final URL that provided the HttpResponse. This will sometimes differ from the original request URI.

.bodybytes

The content of the HTTP response as bytes

.cookieslist

The cookies to be sent back to the client

.HttpResponse(body, status, headers, cookies, version, time_taken, redirects, responder) ➝ Constructor

http_curl.HttpResponse constructor

  • @params:
    • string body
    • int status
    • dict headers
    • list[string] cookies
    • string version
    • number time_taken
    • int redirects
    • string responder
.write(data)

Writes data to the response stream.

This method should be prefered over writing directly to the body property to prevent unexpected behaviors.

  • @params:
    • string|bytes data
.json(data, status_code)

Writes a json encoded data to the response stream and sets the response Content-Type to application/json. If the status code is given, the response will be sent with the given status code.

  • @params:
    • any data
    • number? status_code
.file(path, status_code)

Writes a file into the response stream and sets the Content-Type to the correct mimetype for the file. If the status code is given, the response will be sent with the given status code.

  • @params:
    • string path
    • number? status_code

Sets a cookie to be send back to a client with the given key and value. When other parameters are given, they are used to construct a correct Set-Cookie header based on their named properties.

  • @params:
    • string key
    • string value
    • string? domain
    • string? path
    • string? expires
    • bool? secure
    • string? extras
.redirect(location, status)

Redirects the client to a new location. This function simultaneously sets the Location header and returns a 30x status code. If the status parameter is not given, the function defaults to 302.

@throw HttpException

@notes:

  • When supplying a status, it must be a 30x
  • @params:
    • string location
    • string? status
.content_type(mimetype)

Sets the content type of the HTTP response.

  • @params:
    • string mimetype