C# Client Library
supabaseView on GitHubThis reference documents every object and method available in Supabase's C# library, supabase. You can use Supabase
to interact with your Postgres database, listen to database changes, invoke Deno Edge Functions, build login and user management functionality, and manage large files.
The C# client library is created and maintained by the Supabase community, and is not an official library. Please be tolerant of areas where the library is still being developed, and — as with all the libraries — feel free to contribute wherever you find issues.
Huge thanks to official maintainer, Joseph Schultz. As well as Will Iverson, Ben Randall, and Rhuan Barros for their help.
Installing
Install from NuGet
You can install Supabase package from nuget.org
Initializing
Initializing a new client is pretty straightforward. Find your project url and public key from the admin panel and pass it into your client initialization function.
Supabase
is heavily dependent on Models deriving from BaseModel
. To interact with the API, one must have the associated model (see example) specified.
Leverage Table
, PrimaryKey
, and Column
attributes to specify names of classes/properties that are different from their C# Versions.
_10var url = Environment.GetEnvironmentVariable("SUPABASE_URL");_10var key = Environment.GetEnvironmentVariable("SUPABASE_KEY");_10_10var options = new Supabase.SupabaseOptions_10{_10 AutoConnectRealtime = true_10};_10_10var supabase = new Supabase.Client(url, key, options);_10await supabase.InitializeAsync();
Fetch data
Performs vertical filtering with SELECT.
- LINQ expressions do not currently support parsing embedded resource columns. For these cases,
string
will need to be used. - When using string Column Names to select, they must match names in database, not names specified on model properties.
- Additional information on modeling + querying Joins and Inner Joins can be found in the
postgrest-csharp README
- By default, Supabase projects will return a maximum of 1,000 rows. This setting can be changed in Project API Settings. It's recommended that you keep it low to limit the payload size of accidental or malicious requests. You can use
range()
queries to paginate through your data. From()
can be combined with ModifiersFrom()
can be combined with Filters- If using the Supabase hosted platform
apikey
is technically a reserved keyword, since the API gateway will pluck it out for authentication. It should be avoided as a column name.
_19// Given the following Model (City.cs)_19[Table("cities")]_19class City : BaseModel_19{_19 [PrimaryKey("id")]_19 public int Id { get; set; }_19_19 [Column("name")]_19 public string Name { get; set; }_19_19 [Column("country_id")]_19 public int CountryId { get; set; }_19_19 //... etc._19}_19_19// A result can be fetched like so._19var result = await supabase.From<City>().Get();_19var cities = result.Models
Insert data
Performs an INSERT into the table.
_20[Table("cities")]_20class City : BaseModel_20{_20 [PrimaryKey("id", false)]_20 public int Id { get; set; }_20_20 [Column("name")]_20 public string Name { get; set; }_20_20 [Column("country_id")]_20 public int CountryId { get; set; }_20}_20_20var model = new City_20{_20 Name = "The Shire",_20 CountryId = 554_20};_20_20await supabase.From<City>().Insert(model);
Update data
Performs an UPDATE on the table.
Update()
is typically called using a model as an argument or from a hydrated model.
_10var update = await supabase_10 .From<City>()_10 .Where(x => x.Name == "Auckland")_10 .Set(x => x.Name, "Middle Earth")_10 .Update();
Upsert data
Performs an UPSERT into the table.
- Primary keys should be included in the data payload in order for an update to work correctly.
- Primary keys must be natural, not surrogate. There are however, workarounds for surrogate primary keys.
_10var model = new City_10{_10 Id = 554,_10 Name = "Middle Earth"_10};_10_10await supabase.From<City>().Upsert(model);
Delete data
Performs a DELETE on the table.
Delete()
should always be combined with Filters to target the item(s) you wish to delete.
_10await supabase_10 .From<City>()_10 .Where(x => x.Id == 342)_10 .Delete();
Call a Postgres function
You can call stored procedures as a "Remote Procedure Call".
That's a fancy way of saying that you can put some logic into your database then call it from anywhere. It's especially useful when the logic rarely changes - like password resets and updates.
_10await supabase.Rpc("hello_world", null);
Using filters
Filters allow you to only return rows that match certain conditions.
Filters can be used on Select()
, Update()
, and Delete()
queries.
Note: LINQ expressions do not currently support parsing embedded resource columns. For these cases, string
will need to be used.
_10var result = await supabase.From<City>()_10 .Select(x => new object[] { x.Name, x.CountryId })_10 .Where(x => x.Name == "The Shire")_10 .Single();
Column is equal to a value
Finds all rows whose value on the stated column
exactly matches the specified value
.
_10var result = await supabase.From<City>()_10 .Where(x => x.Name == "Bali")_10 .Get();
Column is not equal to a value
Finds all rows whose value on the stated column
doesn't match the specified value
.
_10var result = await supabase.From<City>()_10 .Select(x => new object[] { x.Name, x.CountryId })_10 .Where(x => x.Name != "Bali")_10 .Get();
Column is greater than a value
Finds all rows whose value on the stated column
is greater than the specified value
.
_10var result = await supabase.From<City>()_10 .Select(x => new object[] { x.Name, x.CountryId })_10 .Where(x => x.CountryId > 250)_10 .Get();
Column is greater than or equal to a value
Finds all rows whose value on the stated column
is greater than or equal to the specified value
.
_10var result = await supabase.From<City>()_10 .Select(x => new object[] { x.Name, x.CountryId })_10 .Where(x => x.CountryId >= 250)_10 .Get();
Column is less than a value
Finds all rows whose value on the stated column
is less than the specified value
.
_10var result = await supabase.From<City>()_10 .Select("name, country_id")_10 .Where(x => x.CountryId < 250)_10 .Get();
Column is less than or equal to a value
Finds all rows whose value on the stated column
is less than or equal to the specified value
.
_10var result = await supabase.From<City>()_10 .Where(x => x.CountryId <= 250)_10 .Get();
Column matches a pattern
Finds all rows whose value in the stated column
matches the supplied pattern
(case sensitive).
_10var result = await supabase.From<City>()_10 .Filter(x => x.Name, Operator.Like, "%la%")_10 .Get();
Column matches a case-insensitive pattern
Finds all rows whose value in the stated column
matches the supplied pattern
(case insensitive).
_10await supabase.From<City>()_10 .Filter(x => x.Name, Operator.ILike, "%la%")_10 .Get();
Column is a value
A check for exact equality (null, true, false), finds all rows whose value on the stated column
exactly match the specified value
.
_10var result = await supabase.From<City>()_10 .Where(x => x.Name == null)_10 .Get();
Column is in an array
Finds all rows whose value on the stated column
is found on the specified values
.
_10var result = await supabase.From<City>()_10 .Filter(x => x.Name, Operator.In, new List<object> { "Rio de Janiero", "San Francisco" })_10 .Get();
Column contains every element in a value
_10var result = await supabase.From<City>()_10 .Filter(x => x.MainExports, Operator.Contains, new List<object> { "oil", "fish" })_10 .Get();
Contained by value
_10var result = await supabase.From<City>()_10 .Filter(x => x.MainExports, Operator.ContainedIn, new List<object> { "oil", "fish" })_10 .Get();
Match a string
Finds all rows whose tsvector value on the stated column
matches to_tsquery(query).
_10var result = await supabase.From<Quote>()_10 .Select(x => x.Catchphrase)_10 .Filter(x => x.Catchphrase, Operator.FTS, new FullTextSearchConfig("'fat' & 'cat", "english"))_10 .Get();
Match an associated value
- Finds a model given a class (useful when hydrating models and correlating with database)
- Finds all rows whose columns match the specified
Dictionary<string, string>
object.
_10var city = new City_10{_10 Id = 224,_10 Name = "Atlanta"_10};_10_10var model = supabase.From<City>().Match(city).Single();
Don't match the filter
Finds all rows which doesn't satisfy the filter.
_10var result = await supabase.From<Country>()_10 .Select(x => new object[] { x.Name, x.CountryId })_10 .Where(x => x.Name != "Paris")_10 .Get();
Match at least one filter
Finds all rows satisfying at least one of the filters.
_10var result = await supabase.From<Country>()_10 .Where(x => x.Id == 20 || x.Id == 30)_10 .Get();
Using modifiers
Filters work on the row level—they allow you to return rows that only match certain conditions without changing the shape of the rows. Modifiers are everything that don't fit that definition—allowing you to change the format of the response (e.g., setting a limit or offset).
Order the results
Orders the result with the specified column.
_10var result = await supabase.From<City>()_10 .Select(x => new object[] { x.Name, x.CountryId })_10 .Order(x => x.Id, Ordering.Descending)_10 .Get();
Limit the number of rows returned
Limits the result with the specified count.
_10var result = await supabase.From<City>()_10 .Select(x => new object[] { x.Name, x.CountryId })_10 .Limit(10)_10 .Get();
Limit the query to a range
Limits the result to rows within the specified range, inclusive.
_10var result = await supabase.From<City>()_10 .Select("name, country_id")_10 .Range(0, 3)_10 .Get();
Retrieve one row of data
Retrieves only one row from the result. Result must be one row (e.g. using limit), otherwise this will result in an error.
_10var result = await supabase.From<City>()_10 .Select(x => new object[] { x.Name, x.CountryId })_10 .Single();
Create a new user
Creates a new user.
- By default, the user needs to verify their email address before logging in. To turn this off, disable Confirm email in your project.
- Confirm email determines if users need to confirm their email address after signing up.
- If Confirm email is enabled, a
user
is returned butsession
is null. - If Confirm email is disabled, both a
user
and asession
are returned.
- If Confirm email is enabled, a
- When the user confirms their email address, they are redirected to the
SITE_URL
by default. You can modify yourSITE_URL
or add additional redirect URLs in your project. - If SignUp() is called for an existing confirmed user:
- When both Confirm email and Confirm phone (even when phone provider is disabled) are enabled in your project, an obfuscated/fake user object is returned.
- When either Confirm email or Confirm phone (even when phone provider is disabled) is disabled, the error message,
User already registered
is returned.
_10var session = await supabase.Auth.SignUp(email, password);
Listen to auth events
Receive a notification every time an auth event happens.
- Types of auth events:
AuthState.SignedIn
,AuthState.SignedOut
,AuthState.UserUpdated
,AuthState.PasswordRecovery
,AuthState.TokenRefreshed
_16supabase.Auth.AddStateChangedListener((sender, changed) =>_16{_16 switch (changed)_16 {_16 case AuthState.SignedIn:_16 break;_16 case AuthState.SignedOut:_16 break;_16 case AuthState.UserUpdated:_16 break;_16 case AuthState.PasswordRecovery:_16 break;_16 case AuthState.TokenRefreshed:_16 break;_16 }_16});
Sign in a user
Log in an existing user using email or phone number with password.
- Requires either an email and password or a phone number and password.
_10var session = await supabase.Auth.SignIn(email, password);
Sign in a user through OTP
- Requires either an email or phone number.
- This method is used for passwordless sign-ins where a OTP is sent to the user's email or phone number.
- If you're using an email, you can configure whether you want the user to receive a magiclink or a OTP.
- If you're using phone, you can configure whether you want the user to receive a OTP.
- The magic link's destination URL is determined by the
SITE_URL
. You can modify theSITE_URL
or add additional redirect urls in your project.
_10var options = new SignInOptions { RedirectTo = "http://myredirect.example" };_10var didSendMagicLink = await supabase.Auth.SendMagicLink("joseph@supabase.io", options);
Sign in a user through OAuth
Signs the user in using third party OAuth providers.
- This method is used for signing in using a third-party provider.
- Supabase supports many different third-party providers.
_10var signInUrl = supabase.Auth.SignIn(Provider.Github);
Sign out a user
Signs out the current user, if there is a logged in user.
- In order to use the
SignOut()
method, the user needs to be signed in first.
_10await supabase.Auth.SignOut();
Verify and log in through OTP
- The
VerifyOtp
method takes in different verification types. If a phone number is used, the type can either besms
orphone_change
. If an email address is used, the type can be one of the following:signup
,magiclink
,recovery
,invite
oremail_change
. - The verification type used should be determined based on the corresponding auth method called before
VerifyOtp
to sign up / sign-in a user.
_10var session = await supabase.Auth.VerifyOTP("+13334445555", TOKEN, MobileOtpType.SMS);
Retrieve a session
Returns the session data, if there is an active session.
_10var session = supabase.Auth.CurrentSession;
Retrieve a user
Returns the user data, if there is a logged in user.
_10var user = supabase.Auth.CurrentUser;
Update a user
Updates user data, if there is a logged in user.
- In order to use the
UpdateUser()
method, the user needs to be signed in first. - By Default, email updates sends a confirmation link to both the user's current and new email. To only send a confirmation link to the user's new email, disable Secure email change in your project's email auth provider settings.
_10var attrs = new UserAttributes { Email = "new-email@example.com" };_10var response = await supabase.Auth.Update(attrs);
Invokes a Supabase Edge Function.
_10var options = new InvokeFunctionOptions_10{_10 Headers = new Dictionary<string, string> {{ "Authorization", "Bearer 1234" }},_10 Body = new Dictionary<string, object> { { "foo", "bar" } }_10};_10_10await supabase.Functions.Invoke("hello", options: options);
Subscribe to channel
Subscribe to realtime changes in your database.
- Realtime is disabled by default for new Projects for better database performance and security. You can turn it on by managing replication.
- If you want to receive the "previous" data for updates and deletes, you will need to set
REPLICA IDENTITY
toFULL
, like this:ALTER TABLE your_table REPLICA IDENTITY FULL;
_20class CursorBroadcast : BaseBroadcast_20{_20 [JsonProperty("cursorX")]_20 public int CursorX {get; set;}_20_20 [JsonProperty("cursorY")]_20 public int CursorY {get; set;}_20}_20_20var channel = supabase.Realtime.Channel("any");_20var broadcast = channel.Register<CursorBroadcast>();_20broadcast.AddBroadcastEventHandler((sender, baseBroadcast) =>_20{_20 var response = broadcast.Current();_20});_20_20await channel.Subscribe();_20_20// Send a broadcast_20await broadcast.Send("cursor", new CursorBroadcast { CursorX = 123, CursorY = 456 });
Unsubscribe from a channel
Unsubscribes and removes Realtime channel from Realtime client.
- Removing a channel is a great way to maintain the performance of your project's Realtime service as well as your database if you're listening to Postgres changes. Supabase will automatically handle cleanup 30 seconds after a client is disconnected, but unused channels may cause degradation as more clients are simultaneously subscribed.
_10var channel = await supabase.From<City>().On(ChannelEventType.All, (sender, change) => { });_10channel.Unsubscribe();_10_10// OR_10_10var channel = supabase.Realtime.Channel("realtime", "public", "*");_10channel.Unsubscribe()
Retrieve all channels
Returns all Realtime channels.
_10var channels = supabase.Realtime.Subscriptions;
Create a bucket
Creates a new Storage bucket
- Policy permissions required:
buckets
permissions:insert
objects
permissions: none
_10var bucket = await supabase.Storage.CreateBucket("avatars");
Retrieve a bucket
Retrieves the details of an existing Storage bucket.
- Policy permissions required:
buckets
permissions:select
objects
permissions: none
_10var bucket = await supabase.Storage.GetBucket("avatars");
List all buckets
Retrieves the details of all Storage buckets within an existing product.
- Policy permissions required:
buckets
permissions:select
objects
permissions: none
_10var buckets = await supabase.Storage.ListBuckets();
Update a bucket
Updates a new Storage bucket
- Policy permissions required:
buckets
permissions:update
objects
permissions: none
_10var bucket = await supabase.Storage.UpdateBucket("avatars", new BucketUpsertOptions { Public = false });
Delete a bucket
Deletes an existing bucket. A bucket can't be deleted with existing objects inside it. You must first empty()
the bucket.
- Policy permissions required:
buckets
permissions:select
anddelete
objects
permissions: none
_10var result = await supabase.Storage.DeleteBucket("avatars");
Empty a bucket
Removes all objects inside a single bucket.
- Policy permissions required:
buckets
permissions:select
objects
permissions:select
anddelete
_10var bucket = await supabase.Storage.EmptyBucket("avatars");
Upload a file
Uploads a file to an existing bucket.
- Policy permissions required:
buckets
permissions: noneobjects
permissions:insert
_10var imagePath = Path.Combine("Assets", "fancy-avatar.png");_10_10await supabase.Storage_10 .From("avatars")_10 .Upload(imagePath, "fancy-avatar.png", new FileOptions { CacheControl = "3600", Upsert = false });
Download a file
Downloads a file.
- Policy permissions required:
buckets
permissions: noneobjects
permissions:select
_10var bytes = await supabase.Storage.From("avatars").Download("public/fancy-avatar.png");
List all files in a bucket
Lists all the files within a bucket.
- Policy permissions required:
buckets
permissions: noneobjects
permissions:select
_10var objects = await supabase.Storage.From("avatars").List();
Replace an existing file
Replaces an existing file at the specified path with a new one.
- Policy permissions required:
buckets
permissions: noneobjects
permissions:update
andselect
_10var imagePath = Path.Combine("Assets", "fancy-avatar.png");_10await supabase.Storage.From("avatars").Update(imagePath, "fancy-avatar.png");
Move an existing file
Moves an existing file, optionally renaming it at the same time.
- Policy permissions required:
buckets
permissions: noneobjects
permissions:update
andselect
_10await supabase.Storage.From("avatars")_10 .Move("public/fancy-avatar.png", "private/fancy-avatar.png");
Delete files in a bucket
Deletes files within the same bucket
- Policy permissions required:
buckets
permissions: noneobjects
permissions:delete
andselect
_10await supabase.Storage.From("avatars").Remove(new List<string> { "public/fancy-avatar.png" });
Create a signed URL
Create signed url to download file without requiring permissions. This URL can be valid for a set number of seconds.
- Policy permissions required:
buckets
permissions: noneobjects
permissions:select
_10var url = await supabase.Storage.From("avatars").CreateSignedUrl("public/fancy-avatar.png", 60);
Retrieve public URL
Retrieve URLs for assets in public buckets
- The bucket needs to be set to public, either via UpdateBucket() or by going to Storage on supabase.com/dashboard, clicking the overflow menu on a bucket and choosing "Make public"
- Policy permissions required:
buckets
permissions: noneobjects
permissions: none
_10var publicUrl = supabase.Storage.From("avatars").GetPublicUrl("public/fancy-avatar.png");
Release Notes
1.0.0 - 2024-04-21
- Assembly Name has been changed to
Supabase.dll
- Update dependency:
postgrest-csharp@5.0.0
- [MAJOR] Moves namespaces from
Postgrest
toSupabase.Postgrest
- Re: #135 Update nuget package
name
postgrest-csharp
toSupabase.Postgrest
- [MAJOR] Moves namespaces from
- Update dependency:
gotrue-csharp@5.0.0
- Re: #135 Update nuget package name
gotrue-csharp
toSupabase.Gotrue
- Re: #89, Only add
access_token
to request body when it is explicitly declared. - [MINOR] Re: #89 Update signature
for
SignInWithIdToken
which adds an optionalaccessToken
parameter, update doc comments, and callDestroySession
in method - Re: #88, Add
IsAnonymous
property toUser
- Re: #90 Implement
LinkIdentity
andUnlinkIdentity
- Re: #135 Update nuget package name
- Update dependency:
realtime-csharp@7.0.0
- Update dependency:
storage-csharp@2.0.0
- Re: #135 Update nuget package
name
storage-csharp
toSupabase.Storage
- Re: #135 Update nuget package
name
- Update dependency:
functions-csharp@2.0.0
- Re: #135 Update nuget package
name
functions-csharp
toSupabase.Functions
- Re: #135 Update nuget package
name
- Update dependency:
core-csharp@1.0.0
- Re: #135 Update nuget package
name
supabase-core
toSupabase.Core
- Re: #135 Update nuget package
name
- Adds comments to the remaining undocumented code.