mangadex-full-api

repository·master·Indexed 41 days ago

https://github.com/md-y/mangadex-full-api

An unofficial wrapper for the MangaDex JSON API supporting Node.js and browser environments. Version 6.2.0 provides high-level abstractions for searching, reading, and uploading manga content, including support for personal client authentication, relationship resolution, and chapter management.

Tokens
10.5K
Snippets
36
Records
61
Agent score
53%

What's inside mangadex-full-api

  1. How Relationships and resolving data work

    master

    MangaDex returns Relationship objects for associated data (like authors or artists) instead of the full object to save bandwidth. To access the actual data, you must use the .resolve() method on the relationship.

    Optimization via includes You can pass an array of strings to the includes parameter in query methods (e.g., Manga.getByQuery({ includes: ['author'] })). This instructs the API to return the associated data immediately. When using includes, the relationship is cached, and calling .resolve() will return the data instantly without a new network request. You can check if a relationship is cached using the .cached property.

    Resolving multiple relationships Use resolveArray() to resolve an array of Relationship objects more efficiently than calling .resolve() on each item individually.

    const manga = await Manga.getRandom();
    
    // Resolve a single relationship
    const firstAuthor = await manga.authors[0].resolve();
    console.log('The first author is', firstAuthor.name);
    
    // Resolve an array of relationships efficiently
    const allAuthors = await resolveArray(manga.authors);
    console.log('All authors are', allAuthors.map((a) => a.name).join(', '));
    
    // Using 'includes' to cache data
    const otherManga = await Manga.getByQuery({ includes: ['author'] });
    if (otherManga) {
        console.log('The authors for this manga are included and cached:', otherManga.authors[0].cached);
        const author = await otherManga.authors[0].resolve();
        console.log('The author is', author.name);
    }
  2. Upload chapters

    master

    To upload a new chapter, follow these steps:

    1. Authenticate using loginPersonal.
    2. Start an upload session using UploadSession.begin(mangaId, [groupId]).
    3. Upload pages as Blob objects using session.uploadPages([...]).
    4. Finalize the upload by calling session.commit(...) with the chapter details (title, volume, language, etc.).
    // 1. Login
    await loginPersonal({
        clientId: 'id',
        clientSecret: 'secret',
        password: 'password',
        username: 'username',
    });
    
    // 2. Begin session
    const session = await UploadSession.begin('manga-id', ['group-id']);
    
    // 3. Upload pages as Blobs
    await session.uploadPages([
        new Blob([fs.readFileSync('path/to/page1.jpg')]),
        new Blob([fs.readFileSync('path/to/page2.jpg')]),
    ]);
    
    // 4. Commit
    await session.commit({
        chapter: '1',
        title: 'A new chapter!',
        translatedLanguage: 'en',
        volume: '1',
    });
  3. Authenticate with a personal account

    master

    To perform actions requiring user authentication (like uploading chapters), use loginPersonal. You must provide a clientId, clientSecret, password, and username obtained from the MangaDex personal client credentials.

    await loginPersonal({
        clientId: 'id',
        clientSecret: 'secret',
        password: 'password',
        username: 'username',
    });
  4. Find manga using search, query, or ID

    master

    There are several ways to locate manga in the library:

    • Manga.search: Perform a keyword search. The limit parameter can accept Infinity to fetch more than the standard API limit of 100 per request.
    • Manga.getByQuery: Retrieve manga based on specific criteria. If you only need one result, this is a convenient way to get the first match.
    • Manga.getRandom: Retrieve a random manga object.
    • Manga.get: Retrieve a specific manga directly using its UUID.
    // Basic Search
    Manga.search({
        title: 'One Piece',
        limit: Infinity,
        hasAvailableChapters: true,
    }).then((mangas) => {
        mangas.forEach((manga) => {
            console.log(manga.localTitle);
        });
    });
    
    // Get first result from a query
    Manga.getByQuery({ title: 'One Piece' }).then((manga) => {
        if (manga) console.log('Found manga id', manga.id);
    });
    
    // Get random manga
    Manga.getRandom().then((manga) => console.log('Random:', manga.localTitle));
    
    // Get by UUID
    Manga.get('manga-uuid-here').then((manga) => console.log(manga));
  5. Retrieve manga page images

    master

    To get the image URLs for a specific chapter, follow this workflow:

    1. Use Manga.getByQuery to find a manga.
    2. Use manga.getFeed to retrieve a list of chapters (you can filter by translatedLanguage).
    3. Use chapter.getReadablePages() on a specific chapter to get the page URLs.
    // Get a manga with chapters
    const manga = await Manga.getByQuery({ order: { followedCount: 'desc' }, availableTranslatedLanguage: ['en'] });
    if (!manga) throw new Error('No manga found!');
    
    // This will get the first English chapter for this manga
    const chapters = await manga.getFeed({ translatedLanguage: ['en'], limit: 1 });
    const chapter = chapters[0];
    
    // Get the image URLs for this chapter
    const pages = await chapter.getReadablePages();
    console.log(pages);
  6. Relationship and Reference Expansion

    master

    The MangaDex API uses a RelationshipSchema to link entities. A relationship contains an id (UUID), a type (e.g., "manga", "user", "tag"), and optional attributes or related metadata.

    Manga Relationship Types: When viewing a manga, relationships can be: "monochrome", "main_story", "adapted_from", "based_on", "prequel", "side_story", "doujinshi", "same_franchise", "shared_universe", "sequel", "spin_off", "alternate_story", "alternate_version", "preserialization", "colored", or "serialization".

    Reference Expansion: To avoid multiple API calls, you can use the includes parameter in requests (like GetMangaIdParamsSchema) to expand related entities. Supported expansions vary by entity type (e.g., for Manga, you can include "author", "artist", "tag", etc.).

  7. Manage Upload Sessions

    master

    The upload process follows a specific lifecycle for uploading images and committing them as chapters:

    1. Start Session: Use POST /upload/begin for a new session or POST /upload/begin/{chapterId} to start an edit session for an existing chapter. This returns an uploadSessionId.
    2. Upload Files: Use POST /upload/{uploadSessionId} to upload binary files to the session. Multiple files can be uploaded sequentially.
    3. Manage Files: You can delete individual files via DELETE /upload/{uploadSessionId}/{uploadSessionFileId} or delete a batch via DELETE /upload/{uploadSessionId}/batch (requires an array of file IDs in the body).
    4. Commit Session: Once files are uploaded, use POST /upload/{uploadSessionId}/commit to finalize the session and specify the chapter data. This converts the session into a permanent chapter.
    5. Abandon Session: If an upload is incomplete or unwanted, use DELETE /upload/{uploadSessionId} to discard the session.
  8. Get MangaDex@Home server URL

    master

    Retrieve the base URL used to construct final image URLs for a specific chapter. The returned URL is valid for the requested chapter only and expires 15 minutes after the response.

    Use the forcePort443 query parameter to ensure the selection of a server using the standard HTTPS port 443, which can help bypass restrictive school or office network filters that block non-standard ports.

    // GET /at-home/server/{chapterId}
    // Query Params:
    // forcePort443?: boolean (default: false)
    
    // Response Body:
    {
      "result"?: "ok",
      "baseUrl"?: string,
      "chapter"?: {
        "hash"?: string,
        "data"?: string[],
        "dataSaver"?: string[]
      }
    }
  9. Configure network origins

    master

    The library provides utility functions to override network settings, which can be useful for debugging or proxying requests:

    • overrideApiOrigin(origin): Sets a custom origin for API calls.
    • overrideAuthOrigin(origin): Sets a custom origin for authentication calls.
    • useDebugServer(url): Enables a debug server for network inspection.
  10. Authentication and User Schemas

    master

    The API provides schemas for managing user sessions and accounts:

    • Login: Use LoginSchema with username or email and a password. Returns a LoginResponseSchema containing session and refresh tokens.
    • Account Creation: Use CreateAccountSchema with username, email, and password.
    • Token Refresh: Use RefreshTokenSchema to provide a token and receive a new session/refresh pair via RefreshResponseSchema.
    • User Profile: UserSchema contains UserAttributesSchema which includes the username and assigned roles.