November 30, 2024
Getting Started with the D&D 5e API in Angular
A Step-by-Step Guide to Building an Angular App with the D&D 5e API

By Thomas George
5 min read
Dungeons & Dragons (D&D) has become a global phenomenon, offering players the chance to dive into an imaginative world filled with monsters, spells, and endless adventure. If you're a developer who's passionate about D&D, or simply want to build a cool tool to interact with the game's rich data, you're in luck! The D&D 5e API is a free and open source resource that provides detailed game data like monsters, spells, and classes, all accessible through a simple REST API.
In this tutorial, we'll walk you through how to integrate the D&D 5e API into an Angular app. By the end, you'll have a working Angular app that can pull data from the API, display it in a user-friendly way, and even handle errors and loading states. So let's get started!
Use Your 404 Pages to Be as Influential as Amazon in Ionic 5 Everyone has done it before. You type in a website then stop and stare at the 404 page that is on the screen. You ask…
What is the D&D 5e API?
Before diving into the code, let's first talk about the D&D 5e API. The API, also known as Open5e, is a public RESTful web service that gives developers access to D&D 5e data, like:
- Monsters — Details about creatures that players can encounter.
- Spells — Information about magical spells available in the game.
- Classes — Character classes such as Fighter, Wizard, Cleric, and more.
- Items, Races, Backgrounds, and More.
You can access this data via simple HTTP requests. For example, to get a list of all monsters, you can make a GET request to [https://www.dnd5eapi.co/api/monsters/](https://www.dnd5eapi.co/api/monsters/.).
Now that you understand the basics of the API, let's build something with it in Angular!
Step 1: Setting Up Your Angular Project
First things first — if you don't already have Angular installed, you'll need to install Angular CLI. Angular CLI is a command-line interface tool that makes it easy to create, manage, and build Angular applications.
To install Angular CLI globally on your system, open your terminal and run the following command:
npm install -g @angular/clinpm install -g @angular/cliNow, you can create a new Angular project by running:
ng new dnd5e-appng new dnd5e-appThis will create a new project called dnd5e-app. Angular CLI will prompt you to choose some basic setup options (like whether to include Angular routing or which stylesheet format to use). Once you've chosen your preferences, navigate into the project directory:
cd dnd5e-appcd dnd5e-appThen, to get your app running, use:
ng serveng serveThis will start a local development server at http://localhost:4200/. You should be able to open this in your browser and see the default Angular page.
**🎉 Everybody Loves Easter Eggs **
- believe everyone has a fond memory of themselves playing one of their favorite games and randomly coming across a…t*
Step 2: Installing Dependencies
To make HTTP requests in Angular, you'll need to use Angular's HttpClient module. The HttpClientModule is part of Angular's standard library, so it's already available to us. If you haven't yet, you'll need to import it into your app.
In the src/app/app.module.ts file, make sure the HttpClientModule is imported:
import { HttpClientModule } from '@angular/common/http';
@NgModule({
declarations: [AppComponent],
imports: [HttpClientModule], // Import HttpClientModule here
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}import { HttpClientModule } from '@angular/common/http';
@NgModule({
declarations: [AppComponent],
imports: [HttpClientModule], // Import HttpClientModule here
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}Step 3: Creating a Service to Interact with the D&D 5e API
In Angular, it's a good practice to separate your logic for interacting with APIs into services. Services provide a clean way to manage your app's data and logic.
We'll now create a service that will handle fetching data from the D&D 5e API.
Run the following command to generate a service file:
ng generate service dnd-aping generate service dnd-apiThis will create a new file called dnd-api.service.ts in your src/app directory. Open the service file and add the following code to create methods that make HTTP requests to the D&D 5e API:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root',
})
export class DndApiService {
private apiUrl = 'https://www.dnd5eapi.co/api';
constructor(private http: HttpClient) {}
// Method to fetch all monsters from the API
getMonsters(): Observable<any> {
return this.http.get(`${this.apiUrl}/monsters`);
}
// Method to fetch all spells
getSpells(): Observable<any> {
return this.http.get(`${this.apiUrl}/spells`);
}
// Method to fetch all character classes
getClasses(): Observable<any> {
return this.http.get(`${this.apiUrl}/classes`);
}
}import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root',
})
export class DndApiService {
private apiUrl = 'https://www.dnd5eapi.co/api';
constructor(private http: HttpClient) {}
// Method to fetch all monsters from the API
getMonsters(): Observable<any> {
return this.http.get(`${this.apiUrl}/monsters`);
}
// Method to fetch all spells
getSpells(): Observable<any> {
return this.http.get(`${this.apiUrl}/spells`);
}
// Method to fetch all character classes
getClasses(): Observable<any> {
return this.http.get(`${this.apiUrl}/classes`);
}
}Here's a breakdown of what's happening:
- We define a
private apiUrlvariable that points to the root of the D&D 5e API. - We then create methods like
getMonsters(),getSpells(), andgetClasses(), each of which uses Angular'sHttpClientto make a GET request to the relevant endpoint of the API.
The Path to Constructive Collaboration: How to Stop Saying "I Wouldn't Have Coded It This Way" and… As developers, we're wired to think critically. It's what makes us good at our jobs. We are able to spot…
Step 4: Using the Service in a Component
Now that we have a service that fetches data from the API, let's use that service in an Angular component. We'll display a list of monsters in this example.
Open the src/app/app.component.ts file and make the following changes:
import { Component, OnInit } from '@angular/core';
import { DndApiService } from './dnd-api.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
monsters: any[] = []; // Array to store monster data
loading: boolean = true; // Flag to track loading state
error: string = ''; // String to hold error messages
constructor(private dndApiService: DndApiService) {}
ngOnInit() {
// Call the service to get monster data when the component initializes
this.dndApiService.getMonsters().subscribe(
(data: any) => {
this.monsters = data.results; // Store the results in the monsters array
this.loading = false; // Set loading to false when data is received
},
(error) => {
this.error = 'Failed to load monsters'; // Set error message if request fails
this.loading = false;
}
);
}
}import { Component, OnInit } from '@angular/core';
import { DndApiService } from './dnd-api.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
monsters: any[] = []; // Array to store monster data
loading: boolean = true; // Flag to track loading state
error: string = ''; // String to hold error messages
constructor(private dndApiService: DndApiService) {}
ngOnInit() {
// Call the service to get monster data when the component initializes
this.dndApiService.getMonsters().subscribe(
(data: any) => {
this.monsters = data.results; // Store the results in the monsters array
this.loading = false; // Set loading to false when data is received
},
(error) => {
this.error = 'Failed to load monsters'; // Set error message if request fails
this.loading = false;
}
);
}
}Now, let's modify the template (src/app/app.component.html) to display the list of monsters:
<!-- Loading message displayed while data is being fetched -->
<div *ngIf="loading">Loading monsters...</div>
<!-- Error message displayed if something goes wrong -->
<div *ngIf="error">{{ error }}</div>
<!-- List of monsters displayed when data is loaded -->
<ul *ngIf="!loading && !error">
<li *ngFor="let monster of monsters">
{{ monster.name }}
</li>
</ul><!-- Loading message displayed while data is being fetched -->
<div *ngIf="loading">Loading monsters...</div>
<!-- Error message displayed if something goes wrong -->
<div *ngIf="error">{{ error }}</div>
<!-- List of monsters displayed when data is loaded -->
<ul *ngIf="!loading && !error">
<li *ngFor="let monster of monsters">
{{ monster.name }}
</li>
</ul>Explanation:
- We initialize an empty array
monstersto store the data. - We set a
loadingflag to show a loading message while the data is being fetched. - In the
ngOnInit()lifecycle hook, we call thegetMonsters()method of theDndApiService, and when the data arrives, we store the list of monsters in themonstersarray. - If an error occurs, we let the player know by displaying an error message.
Step 5: Handling Errors and Loading States
Handling loading states and errors is essential when working with APIs. In the above code, we handle errors by displaying a message if the API request fails. Similarly, the loading state ensures that users are informed that data is being fetched.
You could also take it a step further and display more detailed error messages or retry mechanisms if the request fails multiple times. You can use Angular's built-in tools like HttpInterceptor or third-party libraries like ngx-toastr to handle more complex error scenarios.
Conclusion
In this tutorial, we've covered how to:
- Set up an Angular app using the Angular CLI.
- Install and configure Angular's
HttpClientModule. - Create a service to interact with the D&D 5e API and fetch data.
- Display the fetched data (monsters, in this case) in an Angular component.
- Handle loading and error states to improve the user experience.
From here, you can expand the app by adding more features, such as displaying more data from the API (e.g., spells, classes, or items), implementing search functionality, or even creating a full-fledged D&D companion app.
Building an app with the D&D 5e API is a fun and creative way to practice your Angular skills, and with this foundation, you're ready to dive deeper into both Angular and D&D!
Happy coding, and may your dice rolls always be high!
If you would like to view my previously written articles or connect with me, visit my website by clicking here!