Link Search Menu Expand Document

http

The http 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

echo http.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

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

Creating a server with the http 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
import json

var server = http.server(3000)
server.on_receive(|request, response| {
  echo 'Request from ${request.ip} to ${request.path}.'
  response.headers['Content-Type'] = 'application/json'
  response.write(json.encode(request))
})

echo 'Listening on Port 3000...'
server.listen()

The http 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.

Properties


http.CONTINUE
100 continue
http.SWITCHING_PROTOCOLS
101 switching protocols
http.PROCESSING
102 processing
http.OK
200 ok
http.CREATED
201 created
http.ACCEPTED
202 accepted
http.NON_AUTHORITATIVE_INFORMATION
203 non authoritative information
http.NO_CONTENT
204 no content
http.RESET_CONTENT
205 reset content
http.PARTIAL_CONTENT
206 partial content
http.MULTI_STATUS
207 multi status
http.ALREADY_REPORTED
208 already reported
http.IM_USED
226 im used
http.MULTIPLE_CHOICES
300 multiple choices
http.MOVED_PERMANENTLY
301 moved permanently
http.FOUND
302 found
http.SEE_OTHER
303 see other
http.NOT_MODIFIED
304 not modified
http.USE_PROXY
305 use proxy
http.TEMPORARY_REDIRECT
307 temporary redirect
http.PERMANENT_REDIRECT
308 permanent redirect
http.BAD_REQUEST
400 bad request
http.UNAUTHORIZED
401 unauthorized
http.PAYMENT_REQUIRED
402 payment required
http.FORBIDDEN
403 forbidden
http.NOT_FOUND
404 not found
http.METHOD_NOT_ALLOWED
405 method not allowed
http.NOT_ACCEPTABLE
406 not acceptable
http.PROXY_AUTHENTICATION_REQUIRED
407 proxy authentication required
http.REQUEST_TIMEOUT
408 request timeout
http.CONFLICT
409 conflict
http.GONE
410 gone
http.LENGTH_REQUIRED
411 length required
http.PRECONDITION_FAILED
412 precondition failed
http.PAYLOAD_TOO_LARGE
413 payload too large
http.REQUEST_URI_TOO_LONG
414 request uri too long
http.UNSUPPORTED_MEDIA_TYPE
415 unsupported media type
http.REQUESTED_RANGE_NOT_SATISFIABLE
416 requested range not satisfiable
http.EXPECTATION_FAILED
417 expectation failed
http.TEAPOT
418 teapot
http.MISDIRECTED_REQUEST
421 misdirected request
http.UNPROCESSABLE_ENTITY
422 unprocessable entity
http.LOCKED
423 locked
http.FAILED_DEPENDENCY
424 failed dependency
http.UPGRADE_REQUIRED
426 upgrade required
http.PRECONDITION_REQUIRED
428 precondition required
http.TOO_MANY_REQUESTS
429 too many requests
http.REQUEST_HEADER_FIELDS_TOO_LARGE
431 request header fields too large
http.CONNECTION_CLOSED_WITHOUT_RESPONSE
444 connection closed without response
451 unavailable for legal reasons
http.CLIENT_CLOSED_REQUEST
499 client closed request
http.INTERNAL_SERVER_ERROR
500 internal server error
http.NOT_IMPLEMENTED
501 not implemented
http.BAD_GATEWAY
502 bad gateway
http.SERVICE_UNAVAILABLE
503 service unavailable
http.GATEWAY_TIMEOUT
504 gateway timeout
http.HTTP_VERSION_NOT_SUPPORTED
505 http version not supported
http.VARIANT_ALSO_NEGOTIATES
506 variant also negotiates
http.INSUFFICIENT_STORAGE
507 insufficient storage
http.LOOP_DETECTED
508 loop detected
http.NOT_EXTENDED
510 not extended
http.NETWORK_AUTHENTICATION_REQUIRED
511 network authentication required
http.NETWORK_CONNECT_TIMEOUT_ERROR
599 network connect timeout error
http.map
A map of status code to their string representation.

Functions


http.set_headers(headers: dict)
Sets the request headers for the current module instance.

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

import http
var client = http.set_headers({
  'Authorization': 'Bearer SomeAPIBearerToken',
  'Host': 'example.com',
})
  
echo client.get('/current-user').body.to_string()
returns HttpClient
throws Exception
http.get(url: string)
sends an Http GET request and returns an HttpResponse or throws one of SocketException or Exception if it fails.
returns HttpResponse
throws Exception, SocketExcepion, HttpException
http.post(url: string, [data: string | bytes])
sends an Http POST request and returns an HttpResponse.
returns HttpResponse
throws Exception, SocketExcepion, HttpException
http.put(url: string, [data: string | bytes])
sends an Http PUT request and returns an HttpResponse.
returns HttpResponse
throws Exception, SocketExcepion, HttpException
http.delete(url: string)
sends an Http DELETE request and returns an HttpResponse.
returns HttpResponse
throws Exception, SocketExcepion, HttpException
http.server(port: int, address: string, is_secure: bool)
Creates an new HttpServer instance.
returns HttpServer
throws Exception, SocketExcepion, HttpException

Classes


class HttpRequest


Http request handler and object. @serializable @printable

class HttpRequest properties


HttpRequest.request_uri
The original request URL as sent in the raw request.
type string
HttpRequest.path
The requested path or file. E.g. if the Request URI is /users?sort=desc, then the path is /users.
type string
HttpRequest.method
The HTTP method of the request: GET, POST, PUT, etc.
type string
default GET
HttpRequest.host
The hostname derived from the Host header or the first instance of X-Forwarded-Host if set.
type string
HttpRequest.ip
The IP address of the remote client that initiated the request.
type string
HttpRequest.headers
A dictionary containing the headers sent with the request.
type dictionary
HttpRequest.queries
A dictionary containing the entries of the URI query string.
type dictionary
HttpRequest.cookies
A dictionary containing the cookies sent with the request.
type dictionary
HttpRequest.body
A dictionary containing all data submitted in the request body.
type dictionary
HttpRequest.files
A dictionary containing the data of all files uploaded in the request.
type dictionary
HttpRequest.http_version
The HTTP version used for the request.
type string
HttpRequest.auth_method
The HTTP authentication method to use when the uri contains a credential.
type Auth
default Auth.ANY

class HttpRequest methods


parse(raw_data: string [, client: Socket | TLSSocket])
Parses a raw HTTP request string into a correct HttpRequest
return boolean
send(uri: Url, method: string [, data: string | bytes [, options: dict]])
default follow_redirect: true

class HttpException < Exception


HTTP related Exceptions @printable

class HttpServer


HTTP server @printable

class HttpServer properties


HttpServer.is_secure
A boolean value indicating if the server should/will be TLS/SSL secured or not.
default false
HttpServer.host
The host address to which this server will be bound
default socket.IP_LOCAL (127.0.0.1)
HttpServer.port
The port to which this server will be bound to on the host.
HttpServer.socket
The working Socket instance for the HttpServer.
HttpServer.resuse_address
A boolean value indicating whether to reuse socket addresses or not.
default true
HttpServer.read_timeout
The timeout in milliseconds after which an attempt to read clients request data will be terminated.
default 2000 (2 seconds)
HttpServer.write_timeout
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 2000 (2 seconds)
HttpServer.cert_file
The SSL/TLS ceritificate file that will be used be used by a secured server for serving requests.
  • do not set a value to it directly. Use load_certs() instead.
HttpServer.private_key_file
The SSL/TLS private key file that will be used be used by a secured server for serving requests.
  • do not set a value to it directly. Use load_certs() instead.
HttpServer.verify_certs
This value controls whether the client certificate should be verified or not.
boolean

class HttpServer methods


HttpServer(port: int [, host: string [, is_secure: bool]])
constructor
load_certs(cert_file: string | file [, private_key_file: string | file])
loads the given SSL/TLS certificate pairs for the given SSL/TLS context.
  • certificates can only be loaded for secure servers.
return bool
close()
stops the server
on_connect(fn: function)
Adds a function to be called when a new client connects.
  • Function fn MUST accept at one parameter which will be passed the client Socket object.
  • multiple on_connect() may be set on a single instance.
on_disconnect(fn: function)
Adds a function to be called when a new client disconnects.
  • Function fn MUST accept at one parameter which will be passed the client information.
  • multiple on_disconnect() may be set on a single instance.
on_receive(fn: function)
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.

  • multiple on_receive() may be set on a single instance.
on_reply(fn: function)
Adds a function to be called when the server sends a reply to a client.

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

  • multiple on_sent() may be set on a single instance.
on_error(fn: function)
Adds a function to be called when the server encounters an error with a client.

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

  • multiple on_error() may be set on a single instance.
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.

class HttpClient properties


HttpClient.user_agent
The user agent of the client used to make the request
default Blade HTTP Client/1.0
HttpClient.follow_redirect
Indicates if we receive a redirect from a server, this flag tells us whether we should follow it or not.
default true
HttpClient.skip_hostname_verification
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.
default false
HttpClient.skip_peer_verification
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.
default false
HttpClient.referer
the site that refers us to the current site
default nil
HttpClient.ca_cert
If you have a CA cert for the server stored someplace else than in the default bundle
HttpClient.connect_timeout
The connect timeout duration in milliseconds
default 60s
HttpClient.receive_timeout
The receive timeout duration in milliseconds
default 300s
HttpClient.headers
A dictionary of headers sent along with the request
HttpClient.no_expect
Indicates whether to remove the expect header or not only applies to requests with files in the body
default false

class HttpClient methods


send_request(url: string, [method: string = ‘GET’, data: string])
Sends an Http request and returns a HttpResponse.
default method: GET
return HttpResponse
throws SocketException, Exception
get(url: string)
sends an Http GET request and returns an HttpResponse.
returns HttpResponse
throws Exception, SocketExcepion, HttpException
post(url: string, [data: string | bytes])
sends an Http POST request and returns an HttpResponse.
returns HttpResponse
throws Exception, SocketExcepion, HttpException
put(url: string, [data: string | bytes])
sends an Http PUT request and returns an HttpResponse.
returns HttpResponse
throws Exception, SocketExcepion, HttpException
delete(url: string)
sends an Http DELETE request and returns an HttpResponse.
returns HttpResponse
throws Exception, SocketExcepion, HttpException

class HttpResponse


Represents the response to an Http request @serializable @printable

class HttpResponse properties


HttpResponse.version
The HTTP version of the response
HttpResponse.status
The HTTP response status code
HttpResponse.headers
The HTTP response headers
HttpResponse.time_taken
Total time taken for the HTTP request that generated this HttpResponse to complete
HttpResponse.redirects
The number of times the HTTP request that generated this HttpResponse was redirected.
HttpResponse.responder
The final URL that provided the HttpResponse
  • This might differ from the original request URI.
HttpResponse.body
The content of the HTTP response as bytes

class HttpResponse methods


HttpResponse(body: string, status: int, headers: dict, version: string, time_taken: number, redirects: int, responder: string)
constructor
write(data: string | bytes)
Writes data to the response response.

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


Back to top

Copyright © 2021 Ore Richard Muyiwa. Distributed under the MIT license.