Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
using System.Text.Json.Serialization;
using RestSharp.Authenticators;
namespace RestSharp.Tests.External.Twitter;
public interface ITwitterClient {
Task<TwitterUser> GetUser(string user);
public class TwitterClient : ITwitterClient, IDisposable {
readonly RestClient _client;
public TwitterClient(string apiKey, string apiKeySecret) {
var options = new RestClientOptions("");
_client = new RestClient(options) {
Authenticator = new TwitterAuthenticator("", apiKey, apiKeySecret)
public async Task<TwitterUser> GetUser(string user) {
var response = await _client.GetJsonAsync<TwitterSingleObject<TwitterUser>>(
new { user }
return response!.Data;
record TwitterSingleObject<T>(T Data);
public void Dispose() {
public class TwitterAuthenticator : AuthenticatorBase {
readonly string _baseUrl;
readonly string _clientId;
readonly string _clientSecret;
public TwitterAuthenticator(string baseUrl, string clientId, string clientSecret) : base("") {
_baseUrl = baseUrl;
_clientId = clientId;
_clientSecret = clientSecret;
protected override async ValueTask<Parameter> GetAuthenticationParameter(string accessToken) {
var token = string.IsNullOrEmpty(Token) ? await GetToken() : Token;
return new HeaderParameter(KnownHeaders.Authorization, token);
async Task<string> GetToken() {
var options = new RestClientOptions(_baseUrl);
using var client = new RestClient(options) {
Authenticator = new HttpBasicAuthenticator(_clientId, _clientSecret),
var request = new RestRequest("oauth2/token")
.AddParameter("grant_type", "client_credentials");
var response = await client.PostAsync<TokenResponse>(request);
return $"{response!.TokenType} {response!.AccessToken}";
record TokenResponse {
public string TokenType { get; init; }
public string AccessToken { get; init; }
public record TwitterUser(string Id, string Name, string Username);
Copy link

Cool! Thanks @vanderlei-dev

Copy link

keyse commented May 9, 2023

v107 documentation is not correct.
_client = new RestClient(options)
Authenticator = new TwitterAuthenticator("", apiKey, apiKeySecret)

The above code will NOT compile because Authenticator is getter and can not be set.

Copy link

I appreciate the report, but it would've been better to open an issue in the RestSharp repository rather than commenting on my old gist.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment