Initialize API

This commit is contained in:
2025-07-13 18:46:34 +00:00
parent 365c88e74a
commit d13146cc31
13 changed files with 2552 additions and 77 deletions
+2
View File
@@ -0,0 +1,2 @@
/target
.env
+2
View File
@@ -0,0 +1,2 @@
/target
.env
Generated
+1938
View File
File diff suppressed because it is too large Load Diff
+16
View File
@@ -0,0 +1,16 @@
[package]
name = "api"
version = "1.0.0"
edition = "2024"
[dependencies]
axum = "0.8.4"
bitcode = "0.6.6"
clap = { version = "4.5.41", features = ["derive", "env"] }
dedent = "0.1.1"
dotenvy = "0.15.7"
reqwest = { version = "0.12.22", features = ["json"] }
serde = { version = "1.0.219", features = ["derive"] }
tokio = { version = "1.46.1", features = ["macros", "rt-multi-thread"] }
turbostore = "0.2.0"
urlencoding = "2.1.3"
+10
View File
@@ -0,0 +1,10 @@
FROM rust:latest
WORKDIR /app
COPY . .
RUN cargo build --release
ENTRYPOINT ["cargo"]
CMD ["run", "--release"]
+35 -77
View File
@@ -1,93 +1,51 @@
# API # Nyeki's API
This is a simple API I built for a few utilities I've found myself recoding over and over or using
across projects. The documentation can be found at https://api.nyeki.dev/ and at the root endpoint
if you're self-hosting.
This API provides no stability guarantees (unless you're self-hosting it and modify it). It's not
made for mass usage and with the small set of features it has, if you need something
production-ready you'll be better off writing something yourself.
## Getting started ## Self-hosting
To make it easy for you to get started with GitLab, here's a list of recommended next steps. This API is quite simple to self-host.
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)! Env variables:
## Add your files - `BIND`: The IP:PORT to bind the API to.
- `GITHUB_TOKEN`: A PAT token. You can get one [here](https://github.com/settings/tokens).
- `DISCORD_TOKEN`: A bot token. You can get one [here](https://discord.com/developers/applications/).
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files You can run it using raw Cargo by doing:
- [ ] [Add files using the command line](https://docs.gitlab.com/topics/git/add_files/#add-files-to-a-git-repository) or push an existing Git repository with the following command:
``` ```sh
cd existing_repo $ cargo run --release
git remote add origin https://git.nyeki.dev/nyeki/api.git
git branch -M main
git push -uf origin main
``` ```
## Integrate with your tools The binary has a CLI interface for when you don't have environment variables nor an `.env` file,
you can get help for it with:
- [ ] [Set up project integrations](https://git.nyeki.dev/nyeki/api/-/settings/integrations) ```sh
$ cargo run --release -- --help
```
## Collaborate with your team CLI arguments go after the `--` in the cargo command.
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/) To run deploy the API with Docker, just run:
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Set auto-merge](https://docs.gitlab.com/user/project/merge_requests/auto_merge/)
## Test and Deploy ```sh
$ docker run registry.nyeki.dev/nyeki/api:latest -p 8000:80 \
$ -e DISCORD_TOKEN="..." \
$ -e GITHUB_TOKEN="..."
```
Use the built-in continuous integration in GitLab. You can also clone this repository and run:
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/) ```sh
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/) $ docker build -t nyeki-api .
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html) $ docker run nyeki-api -p 8000:80 \
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/) $ -e DISCORD_TOKEN="..." \
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html) $ -e GITHUB_TOKEN="..."
```
***
# Editing this README
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template.
## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
## Name
Choose a self-explaining name for your project.
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
## License
For open source projects, say how it is licensed.
## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
+35
View File
@@ -0,0 +1,35 @@
import os
import toml
def get_release_version():
"""
Reads the version from the Cargo.toml file.
"""
cargo_toml_path = os.path.join(os.path.dirname(__file__), 'Cargo.toml')
with open(cargo_toml_path, 'r') as f:
cargo_toml = toml.load(f)
return cargo_toml['package']['version']
version = get_release_version()
input(f"The current version is v{version}. Is this properly bumped? (Enter/Ctrl+C)")
script = f"""
docker build -t registry.nyeki.dev/nyeki/api:latest .
docker push registry.nyeki.dev/nyeki/api:latest
docker tag registry.nyeki.dev/nyeki/api:latest registry.nyeki.dev/nyeki/api:v{version}
docker push registry.nyeki.dev/nyeki/api:v{version}
git add .
git commit -m "Release {version} version"
git tag -a v{version} -m "Release version {version}"
git push origin main
git push origin v{version}
"""
os.system(script)
print(f"v{version} was released. Congratulations!")
+16
View File
@@ -0,0 +1,16 @@
use serde::Deserialize;
use turbostore::TurboStore;
#[derive(Debug, Deserialize, Clone, PartialEq, Eq, Hash)]
#[serde(rename_all = "lowercase")]
pub enum Source {
Discord,
GitHub,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Key {
ProfileCacheV1(Source, String),
}
pub type Cache = TurboStore<Key>;
+115
View File
@@ -0,0 +1,115 @@
use std::sync::Arc;
use axum::{Router, routing::get};
use dedent::dedent;
use crate::state::State;
pub mod v1;
pub fn router() -> Router<Arc<State>> {
Router::new()
.route("/", get(docs))
.nest("/v1", v1::router())
}
async fn docs() -> &'static str {
dedent!(
"
Welcome to Nyeki's API! This is a tiny API I built to provide some basic information I
found myself needing in more than one place. This at the moment only includes Discord and
GitHub profiles, but I may add more stuff as I see myself needing it.
The API is versioned, so API endpoints will always be prefixed with `/v{version}`. The
current version is 1 (i.e. stuff is prefixed by `/v1`). All responses are JSON (or
redirects).
The API is not meant to be used by anyone but me, so I don't guarantee that it will always
be available or that it will always return the same data (nor that it's in any way reliable
in production). You're free to use it if you want, but don't expect any serious API
guarantees.
The current endpoints are:
GET /v1/profile
Return's the user's profile (username, name, avatar, banner, and URL).
Query parameters:
- `id`: The ID of the user you want to get the profile of (or their username
for supported sources).
- `source`: The source of the profile (either `discord` or `github`).
Response:
```ts
{
// The user's full username.
\"username\": String,
// The user's name to display.
\"name\": String,
// The URL to the biggest version of the user's avatar. WEBP versions are
// preferred when available.
\"avatar_url\": String,
// The URL to the user's banner, if available.
\"banner_url\": String | null,
// The URL to the user's profile on the source.
\"url\": String,
}
```
GET /v1/profile/avatar
Redirects to the user's avatar URL.
Query parameters:
- `id`: The ID of the user you want to get the profile of (or their username
for supported sources).
- `source`: The source of the profile (either `discord` or `github`).
GET /v1/profile/banner
Redirects to the user's banner URL, or returns nothing if the user has no banner.
Query parameters:
- `id`: The ID of the user you want to get the profile of (or their username
for supported sources).
- `source`: The source of the profile (either `discord` or `github`).
GET /v1/profile/url
Redirects to the user's profile URL on the source.
Query parameters:
- `id`: The ID of the user you want to get the profile of (or their username
for supported sources).
- `source`: The source of the profile (either `discord` or `github`).
They all take 2 query parameters: `id` and `source`. The `id` is the ID of the user you
want to get the profile of, and the `source` is the source of the profile. The source can
be either `discord` or `github`.
For GitHub IDs, numeric IDs will be considered the user's ID, while anything else will be
considered a username. For Discord, they're all snowflakes since there's no API to fetch
users by username. As a sidenote, if you were to want to fetch a Discord user by username,
I'd try to use a user token to send a friend request to the user, then read the ID from the
pending friend requests, fetch the profile, and remove the friend request. Feel free to
play with that (Discord won't like you automating with your user token, it's against ToS).
Errors are quite simple and they all follow the same structure:
```ts
{
// The HTTP status code of the error.
\"status\": Number,
// A human-readable message describing the error.
\"message\": String,
}
```
This API is open source and available at https://git.nyeki.dev/nyeki/api to self-host.
Liked it? Found it useful? A donation would be appreciated! You can do so at
https://ko-fi.com/nyeki.
"
)
}
+302
View File
@@ -0,0 +1,302 @@
mod schemas;
use std::sync::Arc;
use axum::{
Json, Router,
extract::{Query, State as AxumState},
response::Redirect,
routing::get,
};
use reqwest::Client;
use serde::{Deserialize, Serialize};
use turbostore::{Decode, Duration, Encode};
use crate::{cache::Key, state::State};
use crate::{cache::Source, handlers::v1::schemas::Error};
pub fn router() -> Router<Arc<State>> {
Router::new()
.route("/profile", get(get_profile))
.route("/profile/avatar", get(get_profile_avatar))
.route("/profile/banner", get(get_profile_banner))
.route("/profile/url", get(get_profile_url))
.fallback(error_404)
.method_not_allowed_fallback(error_405)
}
async fn error_404() -> Error {
Error {
status: 404,
message: "This endpoint does not exist. Did you make a typo?".into(),
}
}
async fn error_405() -> Error {
Error {
status: 405,
message: "This endpoint does not support this HTTP method".into(),
}
}
#[derive(Debug, Serialize, Encode, Decode)]
struct Profile {
username: String,
name: String,
avatar_url: String,
banner_url: Option<String>,
url: String,
}
#[derive(Debug, Deserialize)]
struct DiscordProfile {
id: String,
username: String,
global_name: Option<String>,
discriminator: String,
avatar: Option<String>,
#[serde(default)]
banner: Option<String>,
}
impl From<DiscordProfile> for Profile {
fn from(value: DiscordProfile) -> Self {
Self {
username: match value.discriminator.as_str() {
"0" => value.username.clone(),
_ => format!("{}#{}", value.username, value.discriminator),
},
name: value.global_name.unwrap_or(value.username),
avatar_url: value
.avatar
.map(|hash| {
format!(
"https://cdn.discordapp.com/avatars/{}/{}.webp?size=256",
value.id, hash
)
})
.unwrap_or_else(|| {
format!(
"https://cdn.discordapp.com/embed/avatars/{}.png?size=256",
match value.discriminator.as_str() {
"0" => (value.id.parse::<u64>().unwrap() >> 22) % 6,
_ => value.discriminator.parse::<u64>().unwrap() % 6,
}
)
}),
banner_url: value.banner.map(|hash| {
format!(
"https://cdn.discordapp.com/banners/{}/{}.webp?size=2048",
value.id, hash
)
}),
url: format!("https://discord.com/users/{}", value.id),
}
}
}
#[derive(Debug, Deserialize)]
struct GitHubProfile {
login: String,
name: Option<String>,
avatar_url: String,
html_url: String,
}
impl From<GitHubProfile> for Profile {
fn from(value: GitHubProfile) -> Self {
Self {
username: value.login.clone(),
name: value.name.unwrap_or(value.login),
avatar_url: value.avatar_url,
banner_url: None,
url: value.html_url,
}
}
}
#[allow(dead_code)]
#[derive(Debug)]
enum FetchError {
Fetch,
Status(u16),
Parsing,
}
trait ToApiError<T> {
fn to_api(self) -> Result<T, Error>;
}
impl<T> ToApiError<T> for Result<T, FetchError> {
fn to_api(self) -> Result<T, Error> {
self.map_err(|error| match error {
FetchError::Fetch => Error {
status: 500,
message: "Could not fetch profile from external source".into(),
},
FetchError::Status(404) => Error {
status: 404,
message: "There was no user for this ID and source".into(),
},
FetchError::Status(_) => Error {
status: 500,
message: "The profile could not be fetched".into(),
},
FetchError::Parsing => Error {
status: 500,
message: "The profile could be fetched, but the data was corrupt".into(),
},
})
}
}
async fn fetch_discord_profile(id: &str, token: &str) -> Result<Profile, FetchError> {
let client = Client::new();
let profile = client
.get(format!(
"https://discord.com/api/v10/users/{}",
urlencoding::encode(id)
))
.header("Authorization", format!("Bot {token}"))
.send()
.await
.map_err(|_| FetchError::Fetch)?
.error_for_status()
.map_err(|err| {
println!("{}", err.url().unwrap());
FetchError::Status(err.status().unwrap().as_u16())
})?
.json::<DiscordProfile>()
.await
.map_err(|_| FetchError::Parsing)?;
Ok(profile.into())
}
async fn fetch_github_profile(id: &str, token: &str) -> Result<Profile, FetchError> {
let client = Client::new();
let profile = client
.get(if id.parse::<u32>().is_ok() {
// Fetch by user ID
format!("https://api.github.com/user/{}", urlencoding::encode(id))
} else {
// Fetch by username
format!("https://api.github.com/users/{}", urlencoding::encode(id))
})
.header("Accept", "application/vnd.github+json")
.header("User-Agent", "NyekisAPI")
.bearer_auth(token)
.send()
.await
.map_err(|_| FetchError::Fetch)?
.error_for_status()
.map_err(|err| {
println!("{}", err.url().unwrap());
FetchError::Status(err.status().unwrap().as_u16())
})?
.json::<GitHubProfile>()
.await
.map_err(|_| FetchError::Parsing)?;
Ok(profile.into())
}
impl ProfileIdentifier {
async fn fetch(&self, state: &State) -> Result<Profile, FetchError> {
match self.source {
Source::Discord => fetch_discord_profile(&self.id, &state.discord_token).await,
Source::GitHub => fetch_github_profile(&self.id, &state.github_token).await,
}
}
}
#[derive(Debug, Deserialize)]
struct ProfileIdentifier {
id: String,
source: Source,
}
async fn get_cached_profile_or_fetch(
state: &State,
identifier: &ProfileIdentifier,
) -> Result<Profile, FetchError> {
let cache = &state.cache;
let cached_profile = cache
.get::<Profile>(&Key::ProfileCacheV1(
identifier.source.clone(),
identifier.id.clone(),
))
.await;
if let Some(profile) = cached_profile {
Ok(profile.unwrap().value)
} else {
let profile = identifier.fetch(state).await?;
cache
.set(
Key::ProfileCacheV1(identifier.source.clone(), identifier.id.clone()),
&profile,
Duration::minutes(15),
)
.await;
Ok(profile)
}
}
async fn get_profile(
AxumState(state): AxumState<Arc<State>>,
Query(identifier): Query<ProfileIdentifier>,
) -> Result<Json<Profile>, Error> {
Ok(Json(
get_cached_profile_or_fetch(&state, &identifier)
.await
.to_api()?,
))
}
async fn get_profile_avatar(
AxumState(state): AxumState<Arc<State>>,
Query(identifier): Query<ProfileIdentifier>,
) -> Result<Redirect, Error> {
let profile = get_cached_profile_or_fetch(&state, &identifier)
.await
.to_api()?;
Ok(Redirect::to(&profile.avatar_url))
}
async fn get_profile_banner(
AxumState(state): AxumState<Arc<State>>,
Query(identifier): Query<ProfileIdentifier>,
) -> Result<Redirect, Error> {
let profile = get_cached_profile_or_fetch(&state, &identifier)
.await
.to_api()?;
profile
.banner_url
.map(|url| Redirect::to(&url))
.ok_or(Error {
status: 404,
message: "The profile does not have a banner".into(),
})
}
async fn get_profile_url(
AxumState(state): AxumState<Arc<State>>,
Query(identifier): Query<ProfileIdentifier>,
) -> Result<Redirect, Error> {
let profile = get_cached_profile_or_fetch(&state, &identifier)
.await
.to_api()?;
Ok(Redirect::to(&profile.url))
}
+20
View File
@@ -0,0 +1,20 @@
use axum::{Json, response::IntoResponse};
use reqwest::StatusCode;
use serde::Serialize;
#[derive(Debug, Serialize)]
pub struct Error {
pub status: u16,
pub message: String,
}
impl IntoResponse for Error {
fn into_response(self) -> axum::response::Response {
(
StatusCode::from_u16(self.status)
.expect("The status code provided was not a valid status code"),
Json(self),
)
.into_response()
}
}
+54
View File
@@ -0,0 +1,54 @@
use std::{sync::Arc, time::Duration};
use axum::Router;
use clap::Parser;
use crate::{cache::Cache, state::State};
pub mod cache;
mod handlers;
mod state;
/// Simple program to greet a person
#[derive(Parser, Debug)]
#[command(version, about, long_about = None)]
struct Args {
/// IP and port to bind the server
#[arg(short, long, default_value_t = String::from("0.0.0.0:8000"), env = "BIND")]
bind: String,
/// Discord bot token
#[arg(long, env = "DISCORD_TOKEN")]
discord_token: String,
/// GitHub PAT with `read:user` scope
#[arg(long, env = "GITHUB_TOKEN")]
github_token: String,
}
#[tokio::main]
async fn main() {
dotenvy::dotenv().ok();
let args = Args::parse();
let state = Arc::new(State {
cache: Cache::default(),
discord_token: args.discord_token,
github_token: args.github_token,
});
let eviction_state = state.clone();
tokio::spawn(async move {
loop {
tokio::time::sleep(Duration::from_secs(10)).await;
eviction_state.cache.evict().await;
}
});
let app = Router::new().merge(handlers::router()).with_state(state);
let listener = tokio::net::TcpListener::bind(args.bind).await.unwrap();
axum::serve(listener, app).await.unwrap();
}
+7
View File
@@ -0,0 +1,7 @@
use crate::cache::Cache;
pub struct State {
pub cache: Cache,
pub discord_token: String,
pub github_token: String,
}