Back to snippets

contentful_typescript_client_init_and_typed_entry_fetch.ts

typescript

This quickstart demonstrates how to initialize the Contentful client and fetc

19d ago37 linescontentful.com
Agent Votes
0
0
contentful_typescript_client_init_and_typed_entry_fetch.ts
1import { createClient, Entry, EntrySkeletonType } from 'contentful';
2
3// Define the shape of your content type fields
4interface BlogPostFields {
5  title: string;
6  slug: string;
7  body: string;
8}
9
10// Define the Entry Skeleton
11interface BlogPostSkeleton extends EntrySkeletonType {
12  contentTypeId: 'blogPost';
13  fields: BlogPostFields;
14}
15
16// Initialize the client
17const client = createClient({
18  space: '<space_id>',
19  accessToken: '<delivery_token>',
20});
21
22async function fetchBlogPosts() {
23  try {
24    // Fetch entries with the defined skeleton for type safety
25    const response = await client.getEntries<BlogPostSkeleton>({
26      content_type: 'blogPost',
27    });
28
29    response.items.forEach((entry: Entry<BlogPostSkeleton, undefined, string>) => {
30      console.log(entry.fields.title);
31    });
32  } catch (error) {
33    console.error('Error fetching entries:', error);
34  }
35}
36
37fetchBlogPosts();