API Reference

This section of the documentation serves to provide a reference guide for developers, tinkerers, engieneers, and explorers for the Replit-py API, and showcases the function and method calls available within the library.

Core

The Replit Python module.

replit.clear()

Clear the terminal.

Return type:

None

Replit Web Framework & Utilities

Make apps quickly using Python.

class replit.web.app.ReplitAuthContext(user_id, name, roles)

Bases: object

A dataclass defining a Replit Auth state.

classmethod from_headers(headers)

Initialize an instance using the Replit identification headers.

Parameters:

headers (dict) – A dictionary of headers received

Returns:

An initialized class instance

Return type:

Any

property is_authed: bool

Check whether the user is authenticated in with Replit Auth.

Returns:

whether or not the authentication is activated.

Return type:

bool

property is_authenticated: bool

Check whether the user is authenticated in with Replit Auth.

Returns:

whether or not the authentication is activated.

Return type:

bool

name: str
roles: str
user_id: int
replit.web.app.debug(app, watch_dirs=None, watch_files=None, **kwargs)

Run the app in debug mode. :type watch_dirs: List[str] :param watch_dirs: Directories whose files will be added to

watch_files. Defaults to [].

Parameters:
  • watch_files (List[str]) – Files to watch, and if changes are detected the server will be restarted. Defaults to [].

  • **kwargs (Any) – Extra keyword arguments to be passed to the flask app’s run method.

Return type:

None

replit.web.app.run(app, host='0.0.0.0', port=8080, change_encoder=True, **kwargs)

A simple wrapper around app.run() with replit compatible defaults.

Return type:

None

Utilities for working with user mappings.

class replit.web.user.User(username, prefix='')

Bases: MutableMapping

A user in the database, usually initialized by UserStore.

db_key()

Returns the database key for this user.

Return type:

str

get(key, default=None)

Gets a value from the database if it exists, otherwise returns default.

Parameters:
  • key (str) – The key to retrieve

  • default (Any) – The value to return if the key does not exist

Returns:

The value of the key or default

Return type:

Any

prefix
set(key, val)

Sets a key to a value for this user’s entry in the database.

Parameters:
  • key (str) – The key to set

  • val (Any) – The value to set it to

Return type:

None

set_value(value)

Sets the raw value of this user in the database.

See set() and get() for a simpler dict based API. Will set the key prefix + username.

Parameters:

value (str) – The value to set in the database

Return type:

None

username
class replit.web.user.UserStore(prefix='')

Bases: Mapping

A mapping of username to keys in the replit database.

property current: User | None

The user currently logged in with repl auth, None if not logged in.

prefix

Utilities to make development easier.

replit.web.utils.authenticated(func=None, login_res='<!DOCTYPE html><html><head><title>Please Sign In</title></head><body><script authed="location.reload()" src="https://replit.com/public/js/repl-auth.js"></script></body></html>')

A decorator that enforces that the user is signed in before accessing the page.

Parameters:
  • func (Callable) – The function passed in if used as a decorator. Defaults to None.

  • login_res (str) – The HTML to show when the user needs to sign in. Defaults to sign_in_snippet.

Returns:

The new handler.

Return type:

Callable

replit.web.utils.authenticated_template(template, **context)

A decorator that renders a template if the user is not signed in.

Parameters:
  • template (str) – The template filename to render.

  • **context (Any) – The context to pass to the template.

Returns:

A decorator to apply to your route.

Return type:

Callable

replit.web.utils.find(data, cond, allow_multiple=False)

Find an item in an iterable.

Parameters:
  • data (Iterable) – The iterable to search through.

  • cond (Callable[[Any], bool]) – The function to call for each item to check if it is a match.

  • allow_multiple (bool) – If multiple result are found, return the first one if allow_multiple is True, otherwise return None.

Returns:

The item if exactly one match was found, otherwise None.

Return type:

Optional[Any]

replit.web.utils.local_redirect(location, code=302)

Perform a redirection to a local path without downgrading to HTTP.

Parameters:
  • location (str) – The path to redirect to.

  • code (int) – The code to use for the redirect. Defaults to 302.

Returns:

The redirect response.

Return type:

flask.Response

replit.web.utils.needs_sign_in(func=None, login_res='<!DOCTYPE html><html><head><title>Please Sign In</title></head><body><script authed="location.reload()" src="https://replit.com/public/js/repl-auth.js"></script></body></html>')

A decorator that enforces that the user is signed in before accessing the page.

Parameters:
  • func (Callable) – The function passed in if used as a decorator. Defaults to None.

  • login_res (str) – The HTML to show when the user needs to sign in. Defaults to sign_in_snippet.

Returns:

The new handler.

Return type:

Callable

replit.web.utils.params(*param_names, src='form', onerror=None)

Require paramaters before a handler can be activated.

Parameters:
  • param_names (str) – The paramaters that must be in the request.

  • src (Union[str, dict]) – The source to get the paramaters from. Can be “form” to use flask.request.form (POST requests), “query” for flask.request.query (GET requests), or a custom dictionary.

  • onerror (Callable) – A function to handle when a paramater is missing. It will be passed the parameter that is missing. If no function is specified a handler that returns a descriptive error and 400 Bad Request status code will be used.

Raises:

TypeError – No paramaters were provided or an invalid one was provided.

Returns:

The new handler.

Return type:

Callable

replit.web.utils.per_user_ratelimit(max_requests, period, login_res='<!DOCTYPE html><html><head><title>Please Sign In</title></head><body><script authed="location.reload()" src="https://replit.com/public/js/repl-auth.js"></script></body></html>', get_ratelimited_res=<function <lambda>>)

Require sign in and limit the amount of requests each signed in user can perform.

This decorator also calls needs_signin for you and passes the login_res kwarg

directly to it.

Parameters:
  • max_requests (int) – The maximum amount of requests allowed in the period.

  • period (float) – The length of the period.

  • login_res (str) – The response to be shown if the user is not signed in, passed to needs_sign_in.

  • get_ratelimited_res (Callable[[float], str]) – A callable which is passed the amount of time remaining before the user can request again and returns the response that should be sent to the user.

Returns:

A function which decorates the handler.

Return type:

Callable[[Callable], flask.Response]

replit.web.utils.sign_in(title='Please Sign In')

Return a sign-in page.

Parameters:

title (str) – The title of the sign in page. Defaults to “Please Sign In”.

Returns:

The sign-in page HTML.

Return type:

str

replit.web.utils.whoami()

Returns the username of the authenticated Replit user, else None.

Return type:

Request

Replit DB

Interface with the Replit Database.

class replit.database.AsyncDatabase(db_url, retry_count=5)

Bases: object

Async interface for Repl.it Database.

client
db_url
async delete(key)

Delete a key from the database.

Parameters:

key (str) – The key to delete

Raises:

KeyError – Key does not exist

Return type:

None

async get(key)

Return the value for key if key is in the database.

This method will JSON decode the value. To disable this behavior, use the get_raw method instead.

Parameters:

key (str) – The key to retreive

Returns:

The value for key if key is in the database.

Return type:

str

async get_raw(key)

Get the value of an item from the database.

Parameters:

key (str) – The key to retreive

Raises:

KeyError – Key is not set

Returns:

The value of the key

Return type:

str

async items()

Convert the database to a dict and return the dict’s items method.

Returns:

The items

Return type:

Tuple[Tuple[str]]

async keys()

Get all keys in the database.

Returns:

The keys in the database.

Return type:

Tuple[str]

async list(prefix)

List keys in the database which start with prefix.

Parameters:

prefix (str) – The prefix keys must start with, blank not not check.

Returns:

The keys found.

Return type:

Tuple[str]

sess
async set(key, value)

Set a key in the database to the result of JSON encoding value.

Parameters:
  • key (str) – The key to set

  • value (Any) – The value to set it to. Must be JSON-serializable.

Return type:

None

async set_bulk(values)

Set multiple values in the database, JSON encoding them.

Parameters:

values (Dict[str, Any]) – A dictionary of values to put into the dictionary. Values must be JSON serializeable.

Return type:

None

async set_bulk_raw(values)

Set multiple values in the database.

Parameters:

values (Dict[str, str]) – The key-value pairs to set.

Return type:

None

async set_raw(key, value)

Set a key in the database to value.

Parameters:
  • key (str) – The key to set

  • value (str) – The value to set it to

Return type:

None

async to_dict(prefix='')

Dump all data in the database into a dictionary.

Parameters:

prefix (str) – The prefix the keys must start with, blank means anything. Defaults to “”.

Returns:

All keys in the database.

Return type:

Dict[str, str]

update_db_url(db_url)

Update the database url.

Parameters:

db_url (str) – Database url to use.

Return type:

None

async values()

Get every value in the database.

Returns:

The values in the database.

Return type:

Tuple[str]

class replit.database.DBJSONEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)

Bases: JSONEncoder

A JSON encoder that uses to_primitive on passed objects.

default(o)

Runs to_primitive on the passed object.

Return type:

Any

class replit.database.Database(db_url, retry_count=5)

Bases: MutableMapping

Dictionary-like interface for Repl.it Database.

This interface will coerce all values everything to and from JSON. If you don’t want this, use AsyncDatabase instead.

close()

Closes the database client connection.

Return type:

None

db_url
dumps(val)

JSON encodes a value that can be a special DB object.

Return type:

str

get(key, default=None)

Return the value for key if key is in the database, else default.

Will replace the mutable JSON types of dict and list with subclasses that enable nested setting. These classes will block to request the DB on every mutation, which can have performance implications. To disable this, use the get_raw method instead.

This method will JSON decode the value. To disable this behavior, use the get_raw method instead.

Parameters:
  • key (str) – The key to retreive

  • default (Any) – The default to return if the key is not the database. Defaults to None.

Returns:

The the value for key if key is in the database, else default.

Return type:

Any

get_raw(key)

Look up the given key in the database and return the corresponding value.

Parameters:

key (str) – The key to look up

Raises:

KeyError – The key is not in the database.

Returns:

The value of the key in the database.

Return type:

str

keys()

Returns all of the keys in the database.

Returns:

The keys.

Return type:

List[str]

prefix(prefix)

Return all of the keys in the database that begin with the prefix.

Parameters:

prefix (str) – The prefix the keys must start with, blank means anything.

Returns:

The keys found.

Return type:

Tuple[str]

sess
set(key, value)

Set a key in the database to value, JSON encoding it.

Parameters:
  • key (str) – The key to set

  • value (Any) – The value to set.

Return type:

None

set_bulk(values)

Set multiple values in the database, JSON encoding them.

Parameters:

values (Dict[str, Any]) – A dictionary of values to put into the dictionary. Values must be JSON serializeable.

Return type:

None

set_bulk_raw(values)

Set multiple values in the database.

Parameters:

values (Dict[str, str]) – The key-value pairs to set.

Return type:

None

set_raw(key, value)

Set a key in the database to value.

Parameters:
  • key (str) – The key to set

  • value (str) – The value to set.

Return type:

None

update_db_url(db_url)

Update the database url.

Parameters:

db_url (str) – Database url to use.

Return type:

None

replit.database.dumps(val)

JSON encode a value in the smallest way possible.

Also handles ObservedList and ObservedDict by using a custom encoder.

Parameters:

val (Any) – The value to be encoded.

Returns:

The JSON string.

Return type:

str

replit.database.make_database_proxy_blueprint(view_only, prefix='')

Generates a blueprint for a database proxy.

Parameters:
  • view_only (bool) – If False, database writing and deletion is enabled.

  • prefix (str) – A prefix that all keys interacted with using this proxy will use.

Returns:

A flask blueprint with the proxy logic.

Return type:

Blueprint

replit.database.start_database_proxy(view_only, prefix='', host='0.0.0.0', port=8080)

Starts the database proxy.

Return type:

None

replit.database.to_primitive(o)

If object is an observed object, converts to primitve, otherwise returns it.

Parameters:

o (Any) – Any object.

Returns:

The primitive equivalent if o is an ObservedList or ObservedDict,

otherwise o.

Return type:

Any

A module containing a database proxy implementation.

replit.database.server.make_database_proxy_blueprint(view_only, prefix='')

Generates a blueprint for a database proxy.

Parameters:
  • view_only (bool) – If False, database writing and deletion is enabled.

  • prefix (str) – A prefix that all keys interacted with using this proxy will use.

Returns:

A flask blueprint with the proxy logic.

Return type:

Blueprint

replit.database.server.start_database_proxy(view_only, prefix='', host='0.0.0.0', port=8080)

Starts the database proxy.

Return type:

None

replit.info module

Information about your repl.

class replit.info.ReplInfo

Bases: object

Represents info about the current repl.

property co_url: str | None

The readable, hosted repl.co URL for this repl.

See id_url for the difference between the hosted URL types.

Returns:

The vanity hosted URL or None if slug or owner is None.

Return type:

Optional[str]

property id: str | None

The id of the repl (REPL_ID environment variable).

property id_co_url: str | None

//<id>.id.repl.co.

Less readable than the vanity URL but guaranteed to work (the vanity URL might be too long for a certificate to be issued for it, causing it to break).

Returns:

The id URL or None if there is no ID.

Return type:

Optional[str]

Type:

The hosted URL of the repl in the form https

property language: str | None

The language of the repl (REPL_LANGUAGE environment variable).

property owner: str | None

The owner of the repl (REPL_OWNER environment variable).

property replit_id_url: str | None

The URL of this repl on replit.com, based on the repl’s ID.

property replit_url: str | None

The URL of this repl on replit.com.

property slug: str | None

The slug of the repl (REPL_SLUG environement variable).

The slug is the url-safe version of the repl’s name.

Returns:

The repl slug.

Return type:

Optional[str]

replit.audio module

A library to play audio in a repl.

class replit.audio.Audio

Bases: object

The basic audio manager.

Notes

This is not intended to be called directly, instead use audio.

Using this in addition to audio can cause major issues.

get_paused()

Get a list of paused sources.

Returns:

A list of sources that are paused.

Return type:

List[Source]

get_playing()

Get a list of playing sources.

Returns:

A list of sources that aren’t paused.

Return type:

List[Source]

get_source(source_id)

Get a source by it’s ID.

Parameters:

source_id (int) – The ID for the source that should be found.

Raises:

NoSuchSourceException – If the source isnt found or there isn’t any sources known to the audio manager.

Returns:

The source with the ID provided.

Return type:

Source

get_sources()

Gets all sources.

Returns:

Every source known to the audio manager, paused or playing.

Return type:

List[Source]

play_file(file_path, volume=1, does_loop=False, loop_count=0, name=None)

Sends a request to play a file, assuming the file is valid.

Parameters:
  • file_path (str) – The path to the file that should be played. Can be absolute or relative.

  • volume (float) – The volume the source should be played at. (1 being 100%)

  • does_loop (bool) – Wether the source should repeat itself or not. Note, if you set this you should also set loop_count.

  • loop_count (int) – How many times the source should repeat itself. Set to 0 to have the source play only once, or set to a negative value for the source to repeat forever.

  • name (str) – The name of the file. Default value is a unique name for the source.

Returns:

The source created with the provided data.

Return type:

Source

Raises:
  • FileNotFoundError – If the file is not found.

  • InvalidFileType – If the file type is not valid.

play_tone(duration, pitch, wave_type, does_loop=False, loop_count=0, volume=1, name=None)

Play a tone from a frequency and wave type.

Parameters:
  • duration (float) – How long the tone should be played (in seconds).

  • pitch (int) – The frequency the tone should be played at.

  • wave_type (WaveType) – The wave shape used to generate the tone.

  • does_loop (bool) – Wether the source should repeat itself or not. Note, if you set this you should also set loop_count.

  • loop_count (int) – How many times the source should repeat itself. Set to 0 to have the source play only once, or set to a negative value for the source to repeat forever.

  • volume (float) – The volume the tone should be played at (1 being 100%).

  • name (str) – The name of the file. Default value is a unique name for the source.

Returns:

The source for the tone.

Return type:

Source

read_status()

Get the raw data for what’s playing.

This is an api call, and shouldn’t be needed for general usage.

Returns:

The contents of /tmp/audioStatus.json

Return type:

AudioStatus

exception replit.audio.InvalidFileType

Bases: Exception

Exception for when a requested file’s type isnt valid.

exception replit.audio.NoSuchSourceException

Bases: Exception

Exception used when a source doesn’t exist.

class replit.audio.Source(payload, loops)

Bases: object

A Source is used to get audio that is sent to the user.

property does_loop: bool

Whether the source repeats itself or not.

property duration: timedelta

The duration of the source.

property end_time: datetime | None

Property wrapper for get_end_time()

get_end_time()

The estimated time when the source will be done playing.

Returns:

The estimated time when the source will be done playing

or None if it is already finished.

Return type:

Optional[datetime]

get_loops_remaining()

The remaining amount of times the file will restart.

Returns:

The number of loops remaining or None if the source can’t be

found, either because it has finished playing or an error occured.

Return type:

Optional[int]

get_paused()

Whether the source is paused.

Return type:

bool

get_remaining()

The estimated time remaining in the source’s current loop.

Return type:

timedelta

get_start_time()

When the source started plaing.

Return type:

datetime

get_volume()

The volume the source is set to.

Return type:

float

property id: int

The ID of the source.

property loops_remaining: int | None

Property wrapper for get_loops_remaining()

property name: str

The name of the source.

property path: str

The path to the source, if available.

property paused: bool

Property wrapper for replit.Source.get_paused and replit.Source.set_paused

property remaining: timedelta

Property wrapper for get_remaining()

set_loop(loop_count)

Set the remaining amount of loops for the source.

Parameters:

loop_count (int) – How many times the source should repeat itself. Set to a negative value for infinite.

Return type:

None

set_paused(paused)

Change if the source is paused.

Parameters:

paused (bool) – Whether the source should be paused.

Return type:

None

set_volume(volume)

Set the volume.

Parameters:

volume (float) – The volume the source should be set to.

Return type:

None

property start_time: datetime

Property wrapper for get_start_time()

toggle_playing()

Play/pause the source.

Return type:

None

property volume: float

Property wrapper for replit.Source.get_volume and replit.Source.set_volume

class replit.audio.types.AudioStatus

Bases: TypedDict

The raw data read from /tmp/audioStatus.json.

Disabled: bool

Wether the audio manager is disabled or not.

Type:

bool

Running: bool

Wether the audio manager knows any sources or not.

Type:

bool

Sources: List[SourceData]

The sources that are know to the audio manager.

Type:

List[SourceData]

class replit.audio.types.ReaderType(value, names=None, *values, module=None, qualname=None, type=None, start=1, boundary=None)

Bases: Enum

An Enum for the types of sources.

aiff_file = 'aiff'

The type for a .aiff file.

Type:

ReaderType

mp3_file = 'mp3'

The type for a .mp3 file.

Type:

ReaderType

tone = 'tone'

The type for a generated tone.

Type:

ReaderType

wav_file = 'wav'

The type for a .wav file.

Type:

ReaderType

class replit.audio.types.RequestArgs

Bases: TypedDict

The additional arguments for a request that are type-specific.

Path: str

The path to the file to be read. Only used if the request is for a file type.

Type:

str

Pitch: float

The pitch/frequency of the tone. Only used if the request type is tone.

Type:

float

Seconds: float

The duration for the tone to be played. Only used if the request type is tone.

Type:

float

WaveType: WaveType

The wave type of the tone. Only used if the request type is tone.

Type:

WaveType

class replit.audio.types.RequestData

Bases: TypedDict

A request to pid1 for a source to be played.

Args: RequestArgs

The additional arguments for the source.

Type:

RequestArgs

DoesLoop: bool

Wether the source should loop / repeat or not. Defaults to false.

Type:

bool

ID: int

The ID of the source. Only used for updating a pre-existing source.

Type:

int

LoopCount: int

How many times the source should loop / repeat. Defaults to 0.

Type:

int

Name: str

The name of the source.

Type:

str

Paused: bool

Wether the source with the provided ID should be paused or not. Can only be used when updating a source.

Type:

bool or None

Type: ReaderType

The type of the source.

Type:

ReaderType

Volume: float

The volume the source should be played at. (1 being 100%)

Type:

float

class replit.audio.types.SourceData

Bases: TypedDict

A source’s raw data, as a payload.

Duration: int

The duration of the source in milliseconds.

Type:

int

EndTime: str

The estimated timestamp for when the source will finish playing.

Type:

str

ID: int

The ID of the source.

Type:

int

Loop: int

How many times the source will loop. If 0, the source will not repeat itself.

Type:

int

Name: str

The name of the source.

Type:

str

Paused: bool

Wether the source is paused or not.

Type:

bool

Remaining: int

How many more milliseconds the source will be playing.

Type:

int

Request: RequestData

The request used to create the source.

Type:

RequestData

StartTime: str

When the source started playing.

Type:

str

Type: str

The type of the source.

Type:

str

Volume: float

The volume of the source.

Type:

float

class replit.audio.types.WaveType(value, names=None, *values, module=None, qualname=None, type=None, start=1, boundary=None)

Bases: Enum

The different wave shapes that can be used for tone generation.

WaveSaw = 2

The Saw wave shape.

Type:

WaveType

WaveSine = 0

The WaveSine wave shape.

Type:

WaveType

WaveSqr = 3

The Square wave shape.

Type:

WaveType

WaveTriangle = 1

The Triangle wave shape.

Type:

WaveType

replit.audio.types.file_types: List[ReaderType] = [ReaderType.aiff_file, ReaderType.wav_file, ReaderType.mp3_file]

The different file types for sources in a list.