In today’s fast-paced digital world, integrating advanced AI capabilities into your applications can significantly enhance user experiences, improve efficiency, and automate processes. One powerful tool to achieve this is the Perplexity API, which offers advanced conversational AI and real-time data processing features. Whether you’re building intelligent chatbots, virtual assistants, or extracting valuable insights from large datasets, the Perplexity API can help you create smarter applications with ease.
In this guide, we’ll walk you through the steps to get started with the Perplexity API, from setting up your API key to testing the API and utilizing its chat completion features. By the end of this guide, you’ll be ready to integrate the Perplexity API into your projects, making them more interactive, efficient, and user-friendly.
Step 1: Create an Account and Obtain an API Key
- Click on the Account button located in the left sidebar of the Perplexity homepage.
- Select API from the menu options.
- Navigate to the API Keys section.
- Click on Generate Keys to create your API key.

The Perplexity API key generation process is essential for securely authenticating and interacting with the Perplexity API. After generating your API key, you’ll use it in all subsequent API requests to access the services.
Step 2: Install the Perplexity SDK
Perplexity provides official SDKs for Python and JavaScript, making it easier to integrate their services into your projects. Here’s how to install the Perplexity SDK for Python:
For Python:
pip install perplexityai
This command will install the Perplexity API SDK, which enables seamless API calls in your Python environment.
Step 3: Make Your First API Call
Once the SDK is installed, it’s time to make your first API call and retrieve real-time web search results. The following Python code demonstrates how to make a simple search query using the Perplexity API:
Python Example:
from perplexity import Perplexity
# Initialize the client
client = Perplexity()
# Perform a search query
search = client.search.create(
query="latest AI developments 2024",
max_results=5,
max_tokens_per_page=1024
)
# Display the results
for result in search.results:
print(f"{result.title}: {result.url}")
This script searches for the latest AI developments and prints the titles and URLs of the top results.
Step 4: Utilize Chat Completions
Perplexity’s API also supports chat completions, allowing you to integrate conversational AI capabilities.
Python Example:
from perplexity import Perplexity
# Initialize the Perplexity client
client = Perplexity(api_key="YOUR_API_KEY")
# Send a chat message and get a response
response = client.chat.create(
model="sonar", # Assuming the "sonar" model is used for chat completions
messages=[
{"role": "user", "content": "What is the latest news on AI?"}
],
temperature=0.2,
max_tokens=100
)
# Print the response
print(response['choices'][0]['message']['content'])
This script queries the Perplexity API for the latest AI developments and prints the titles and URLs of the top results. It provides a quick introduction to retrieving data from the API and processing it.
Here’s a step-by-step explanation of what each part of the code does:
1. Import the Perplexity SDK
- First, the code imports the Perplexity class from the Perplexity SDK. This is necessary to interact with the Perplexity API and access its various functionalities, such as sending messages and receiving responses.
2. Initialize the Perplexity Client
- The Perplexity client is initialized with your API key, which authenticates your request to the Perplexity API. This client will be used to interact with the API and send the requests.
3. Send a Chat Message
- The
client.chat.create()method is called to send a chat message to the Perplexity model.- Model: The
model="sonar"specifies which Perplexity model to use. In this case, the"sonar"model is chosen, which is suitable for generating conversational responses. - Messages: This is a list containing the conversation. Each message in the list has:
- Role: The role of the sender, such as
"user"(the person asking the question) or"system"(if there’s an instruction to the model). - Content: The actual message or question being asked. In this case, the user asks, “What is the latest news on AI?”
- Role: The role of the sender, such as
- Temperature: The temperature controls the randomness of the response. A lower value (0.2) makes the model’s response more focused and deterministic, meaning it will provide a more predictable and concise answer.
- Max Tokens: The max_tokens parameter limits how long the response can be, setting a cap on the number of tokens (or words) in the output. Here, it’s limited to 100 tokens.
- Model: The
4. Extract the Response
- After sending the message, the response from the Perplexity API is stored in the
responseobject. - The choices array in the response contains the model’s output. Since the API might generate multiple responses, the code accesses the first response in the array.
- The message content of the response is accessed using the path
response['choices'][0]['message']['content'], and this is the actual text the model has generated as the answer to the user’s question.
5. Display the Response
Finally, the content of the generated response is printed to the console, allowing you to see what the model has replied to the user’s query. The output will typically be a concise answer based on the model’s interpretation of the question, in this case, about the latest developments in AI.
Step 5: Testing the Perplexity API in Postman
1. Install Postman
If you don’t have Postman installed already, download and install it from here
2. Create a New Request
- Open Postman.
- Click on the “New” button (usually in the top left corner).
- Select Request.
- Choose a collection or create a new one.
- Enter a name for the request and click “Save”.
3. Set Up the Request
In Postman, you can set up a request by specifying the following details:
- Request Type: Select
POSTfor making data requests. - URL: Enter the Perplexity API endpoint URL. For example, for a search query, you might use:
https://api.perplexity.ai/chat/completions
This is the endpoint URL where you are sending the API request to interact with the Perplexity model, specifically for generating chat completions.
- Headers: Set the authentication header.
- Click on the Headers tab below the URL.
- Add the
Authorizationheader with your API key:
Key: Authorization
Value: Bearer YOUR_API_KEY
- Replace
YOUR_API_KEYwith the API key you obtained earlier.
- Body: Choose the raw option and select
JSONfrom the dropdown menu.
For example, to send a simple query for the latest AI developments, use the following JSON body:
{
"model": "sonar",
"messages": [
{
"role": "system",
"content": "Be precise and concise."
},
{
"role": "user",
"content": "How many stars are there in our galaxy?"
}
]
}
model: "sonar"
- What it is: This tells the API which model to use for generating the response. In this case, the model is named
sonar. The model is trained to handle tasks like text generation and chat completions.
messages: This is an array of messages in the conversation.
- First Message (system message):
role: “system”: This indicates the message is from the system (the AI’s setup instructions).content: “Be precise and concise.”: This is an instruction to the AI to give a precise and concise answer. This helps set the tone for the model’s responses.
- Second Message (user message):
role: “user”: This indicates the message is from the user (the question being asked).content: “How many stars are there in our galaxy?”: This is the user’s question about the number of stars in the Milky Way galaxy.
4. Send the Request
Once everything is set up:
- Click on the Send button at the top right.
- Wait for the response. You should see the results returned from the API in the Response section.
5. Review the Response
After sending the request, you will receive a response from the Perplexity API. This will typically be in JSON format.
For example, a successful search query might return something like:
{
"id": "b142094c-550e-43c6-af03-6f006604dab0",
"model": "sonar",
"created": 1761670023,
"usage": {
"prompt_tokens": 14,
"completion_tokens": 273,
"total_tokens": 287,
"search_context_size": "low",
"cost": {
"input_tokens_cost": 0.0,
"output_tokens_cost": 0.0,
"request_cost": 0.005,
"total_cost": 0.005
}
},
"citations": [
"https://www.discovermagazine.com/how-many-stars-are-in-the-milky-way-more-than-you-can-imagine-48126",
"https://astro.arizona.edu/news/how-many-stars-are-milky-way-more-you-can-imagine",
"https://bigthink.com/starts-with-a-bang/how-many-stars-milky-way/",
"https://www.esa.int/Science_Exploration/Space_Science/How_many_stars_are_there_in_the_Universe",
"https://en.wikipedia.org/wiki/Milky_Way",
"https://imagine.gsfc.nasa.gov/science/objects/milkyway1.html",
"https://science.nasa.gov/universe/stars/",
"https://www.space.com/25959-how-many-stars-are-in-the-milky-way.html"
],
"search_results": [
{
"title": "How Many Stars Are in The Milky Way? More Than You Can Imagine",
"url": "https://www.discovermagazine.com/how-many-stars-are-in-the-milky-way-more-than-you-can-imagine-48126",
"date": "2025-10-13",
"last_updated": "2025-10-28",
"snippet": "Astronomers believe there are about 100 billion stars in the Milky Way. But, this number of stars depends on various factors.",
"source": "web"
},
{
"title": "How Many Stars Are in The Milky Way? More Than You Can Imagine",
"url": "https://astro.arizona.edu/news/how-many-stars-are-milky-way-more-you-can-imagine",
"date": "2025-10-14",
"last_updated": "2025-10-28",
"snippet": "Astronomers believe there are about 100 billion stars in the Milky Way. But, this number of stars depends on various factors.",
"source": "web"
},
{
"title": "Why we still don't know how many stars are in the Milky Way",
"url": "https://bigthink.com/starts-with-a-bang/how-many-stars-milky-way/",
"date": "2025-04-02",
"last_updated": "2025-09-23",
"snippet": "While the most commonly cited figure is around 200 billion stars, some sources still cite a lower value of as little as 100 billion, while other ...",
"source": "web"
},
{
"title": "How many stars are there in the Universe? - European Space Agency",
"url": "https://www.esa.int/Science_Exploration/Space_Science/How_many_stars_are_there_in_the_Universe",
"date": "2020-06-01",
"last_updated": "2025-10-28",
"snippet": "Astronomers estimate there are about 100 thousand million stars in the Milky Way alone. Outside that, there are millions upon millions of other galaxies also!",
"source": "web"
},
{
"title": "Milky Way - Wikipedia",
"url": "https://en.wikipedia.org/wiki/Milky_Way",
"date": "2001-09-15",
"last_updated": "2025-10-27",
"snippet": "It is estimated to contain 100–400 billion stars and at least that number of planets. The Solar System is located at a radius of about 27,000 light ...",
"source": "web"
},
{
"title": "Milky Way Galaxy - Imagine the Universe! - NASA",
"url": "https://imagine.gsfc.nasa.gov/science/objects/milkyway1.html",
"date": "2015-07-22",
"last_updated": "2025-10-24",
"snippet": "Our best estimates tell us that the Milky Way is made up of approximately 100 billion stars. These stars form a large disk whose diameter is about 100,000 light ...",
"source": "web"
},
{
"title": "Star Basics - NASA Science",
"url": "https://science.nasa.gov/universe/stars/",
"date": "2025-05-02",
"last_updated": "2025-10-28",
"snippet": "Our Milky Way alone contains more than 100 billion, including our most well-studied star, the Sun.",
"source": "web"
},
{
"title": "How Many Stars Are in the Milky Way? - Space",
"url": "https://www.space.com/25959-how-many-stars-are-in-the-milky-way.html",
"date": "2021-06-09",
"last_updated": null,
"snippet": "The Gaia mission, in orbit since 2013, has managed to map positions of 1.7 billion stars in the sun's neigborhood up to the distance of 326 ...",
"source": "web"
}
],
"object": "chat.completion",
"choices": [
{
"index": 0,
"finish_reason": "stop",
"message": {
"role": "assistant",
"content": "The Milky Way galaxy contains approximately **100 billion to 400 billion stars**, with the most commonly cited estimates around **200 billion stars**. The wide range reflects uncertainty mainly due to difficulties in detecting the numerous faint, low-mass stars such as red dwarfs[3][5][7].\n\nKey points supporting this range:\n\n- Earlier estimates often cited about 100 billion stars[1][2][6][7], but newer data, particularly from ESA's Gaia mission, suggest the actual number could be around 200 billion or more, possibly up to 400 billion[3].\n\n- The primary uncertainty comes from the lowest-mass stars, which are very faint and hard to detect, making it challenging to count them accurately[3].\n\n- The Milky Way is a large spiral galaxy with a stellar disk about 100,000 light-years across, containing stars of various types and masses distributed unevenly, including dense central regions and more diffuse outer halo[5][6].\n\nThus, while 100 billion is a useful lower-bound figure often stated for simplicity, the best current scientific understanding places the number of stars in the Milky Way between **200 billion and 400 billion**[3][5].\n\nNo definitive single number exists because of observational limitations, but estimates beyond 400 billion are generally considered unlikely given the known stellar mass and luminosity data[3]."
},
"delta": {
"role": "assistant",
"content": ""
}
}
]
}
Response Fields Explained:
content: The actual answer to the user’s question, in this case, providing information on how many stars are in the Milky Way galaxy.
id:"b142094c-550e-43c6-af03-6f006604dab0"
This is a unique identifier for this specific API response. It helps to track and manage requests and responses.
model:"sonar"
This indicates the model used to generate the response. In this case, it’s the sonar model, which is likely designed for chat-based interactions.
created:1761670023
This is a timestamp (in UNIX format) representing when the response was created.
usage:- This section gives details about how many tokens were used during the request.
prompt_tokens:14– This indicates the number of tokens (words or characters) used in the input text (your query).
completion_tokens:273– This shows how many tokens were used in the AI’s response.
total_tokens:287– Total number of tokens used (sum ofprompt_tokensandcompletion_tokens).
cost: Details the cost of the API call in terms of tokens and request usage.
request_cost: The cost of processing the request (in dollars).
total_cost: The overall cost for both input and output tokens.
citations:- This is a list of links to external sources that were referenced by the model in generating the response. It gives you more information about the topic.
search_results:- These are relevant search results related to the query. They include links to websites, a short snippet of text, and publication dates. Example:
title: The title of the article.
url: The direct URL to the article.
snippet: A brief excerpt from the article.
source: Where the information came from (in this case, it says “web”).
object:"chat.completion"
This indicates that the object returned is a chat completion, meaning the response is based on a conversational context.
choices:- This is an array containing the model’s responses.
index: The index of the response in case multiple completions were requested.
finish_reason:"stop"– This means the model has finished generating the response.
message:
role:"assistant"– This indicates that the message is generated by the assistant (the AI).

Use Cases and Applications of the Perplexity API
The Perplexity API offers a wide range of real-world applications, making it an invaluable tool for businesses and developers looking to leverage the power of AI-driven solutions. Here are some key use cases:
- Customer Support Bots:
Integrate the Perplexity API into your customer support system to offer instant, AI-driven responses, reducing the workload on human agents and improving user experience. - AI-Powered Virtual Assistants:
Build intelligent virtual assistants that understand and respond to a wide variety of user requests, improving productivity and user satisfaction. - Knowledge Extraction from Large Datasets:
Extract valuable insights from large datasets, such as research papers and company knowledge bases, with the Perplexity API. - Content Generation and Summarization:
Automate content creation for blogs, marketing materials, and social media posts using the Perplexity API, saving time and effort in content production.
Conclusion
The Perplexity API offers a powerful and flexible solution for integrating advanced AI capabilities into your applications, from conversational assistants to real-time data analysis. By following the steps outlined in this guide, you can quickly get started with the Perplexity API and unlock its full potential for automating tasks, improving user experiences, and driving business efficiency.
Whether you’re building intelligent chatbots, extracting insights from large datasets, or creating dynamic content, the Perplexity API provides the tools you need to enhance your projects. Ready to take your applications to the next level? Sign up for the Perplexity API today, generate your API key, and start exploring its capabilities with ease!
Don’t wait – start integrating the Perplexity API and leverage the power of AI in your projects today.
FAQ
1. How to set up Perplexity API?
To set up the Perplexity API, you need to:
- Sign up on the Perplexity platform.
- Navigate to the API section and generate your Perplexity API key.
- Install the Perplexity SDK using the
pip install perplexityaicommand. - Use the API key to authenticate and make requests to the API endpoints.
2. How to use Perplexity sonar API?
To use the Perplexity sonar API, you need to:
- Initialize the Perplexity client with your API key.
- Send a chat message using the
client.chat.create()method. - Specify the sonar model and pass the conversation messages.
- Set parameters like temperature and max_tokens to control the response.
- Retrieve the response and use it in your application.
3. How to create a Perplexity API?
Creating a Perplexity API requires you to:
- Create an account on the Perplexity platform.
- Navigate to the API section in your account dashboard.
- Generate your API key to start making API requests.
- The generated key will authenticate and authorize your API calls.
4. Does Perplexity AI have an API?
Yes, Perplexity AI provides a powerful API that allows developers to integrate its advanced AI models into applications. The Perplexity API supports chat completions, search queries, and knowledge extraction, offering seamless integration for building AI-driven solutions.
Explore More About Perplexity
If you’re fascinated by the potential of Perplexity API and want to dive deeper into AI development, we’ve got you covered! You can explore more articles in our Perplexity category or check out the following blogs:
- Welcome to the AI Dev Series: Why Perplexity Is Worth Exploring – A deep dive into why Perplexity is a game-changer for developers and businesses.
- Perplexity vs ChatGPT: Developer Perspective – Compare and contrast Perplexity with ChatGPT to see how each AI platform can help with different development needs.
Stay tuned for more insights, and start integrating Perplexity API into your projects today!

Comments