Make Your First API Request
A step-by-step guide to making your first Nexus API request
Overview
This guide will walk you through the process of making your first API request to the Nexus platform. By the end, you'll have a working example that retrieves data from our Maps API and displays it in your application.
We'll cover:
- Creating an account and getting an API key
- Setting up your development environment
- Making a simple API request
- Understanding the response
- Next steps for building with Nexus
Prerequisites
Before you begin, make sure you have the following:
- A Nexus account (we'll create one in Step 1)
- Basic knowledge of your preferred programming language
- A code editor or IDE
- A way to run HTTP requests (curl, Postman, or your programming language's HTTP client)
Create an Account & Get an API Key
First, you'll need to create a Nexus account and get an API key to authenticate your requests.
- Go to the Nexus Dashboard and create an account.
- After creating your account, navigate to the API Keys section in your dashboard.
- Click Create New API Key, give it a name (like "My First API Key"), and select the APIs you want to access (for this tutorial, select "Maps API").
- Copy your new API key and keep it secure. Never share your API key publicly or commit it to version control.
Security Tip
Your API key is like a password - it should be kept secure. For client-side applications (like JavaScript in a browser), you should implement restrictions for your API key in the Nexus Dashboard (under API Key settings > Restrictions). Consider setting allowed domains, IP addresses, or using a proxy server in production.
Set Up Your Development Environment
Now that you have an API key, let's set up a simple development environment to make API requests. Choose your preferred method below:
If you're using cURL, you're already set! You can run cURL commands directly from your terminal. Make sure you have cURL installed by running:
curl --version
If not installed, you can download it here.
For JavaScript, create a new HTML file (e.g., nexus-api-test.html) with the following structure:
<!DOCTYPE html>
<html>
<head>
<title>Nexus API Test</title>
</head>
<body>
<h1>Nexus API Test</h1>
<div id="result"></div>
<script>
// We'll add our API request code here
const apiKey = 'YOUR_API_KEY'; // Replace with your actual API key
</script>
</body>
</html>
For Python, make sure you have the requests library installed:
pip install requests
Then create a new Python file (e.g., nexus_api_test.py):
import requests
# Replace with your actual API key
api_key = 'YOUR_API_KEY'
# We'll add our API request code here
Make Your First API Request
Now, let's make a simple API request to get information about a location using the Maps API. We'll use the Geocoding endpoint to convert an address to geographic coordinates (latitude and longitude).
curl -X GET "https://api.nexus-platform.com/v2/maps/geocode?address=1600+Pennsylvania+Ave+NW,+Washington,+DC" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json"
Replace YOUR_API_KEY with the API key you created in Step 1.
Add the following code to your HTML file's <script> section:
// Function to make the API request
async function geocodeAddress() {
const address = '1600 Pennsylvania Ave NW, Washington, DC';
const url = `https://api.nexus-platform.com/v2/maps/geocode?address=${encodeURIComponent(address)}`;
try {
const response = await fetch(url, {
method: 'GET',
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
}
});
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json();
displayResult(data);
} catch (error) {
console.error('Error fetching data:', error);
document.getElementById('result').innerHTML = `Error: ${error.message}
`;
}
}
// Function to display the result
function displayResult(data) {
const resultElement = document.getElementById('result');
if (data.status === 'OK' && data.results.length > 0) {
const location = data.results[0].geometry.location;
const formattedAddress = data.results[0].formatted_address;
resultElement.innerHTML = `
Geocoding Result
Address: ${formattedAddress}
Coordinates: Latitude: ${location.lat}, Longitude: ${location.lng}
${JSON.stringify(data, null, 2)}
`;
} else {
resultElement.innerHTML = `No results found or error occurred.
`;
}
}
// Call the function when the page loads
window.onload = geocodeAddress;
Replace YOUR_API_KEY with the API key you created in Step 1.
Open the HTML file in your browser to see the result.
Add the following code to your Python file:
def geocode_address():
address = '1600 Pennsylvania Ave NW, Washington, DC'
url = f'https://api.nexus-platform.com/v2/maps/geocode'
headers = {
'Authorization': f'Bearer {api_key}',
'Content-Type': 'application/json'
}
params = {
'address': address
}
try:
response = requests.get(url, headers=headers, params=params)
response.raise_for_status() # Raise exception for HTTP errors
data = response.json()
display_result(data)
except requests.exceptions.RequestException as e:
print(f'Error fetching data: {e}')
def display_result(data):
if data.get('status') == 'OK' and len(data.get('results', [])) > 0:
location = data['results'][0]['geometry']['location']
formatted_address = data['results'][0]['formatted_address']
print('Geocoding Result:')
print(f'Address: {formatted_address}')
print(f'Coordinates: Latitude: {location["lat"]}, Longitude: {location["lng"]}')
print('\nFull Response:')
import json
print(json.dumps(data, indent=2))
else:
print('No results found or error occurred.')
# Call the function
if __name__ == '__main__':
geocode_address()
Replace YOUR_API_KEY with the API key you created in Step 1.
Run the Python file to see the result.
Understanding the Response
After making the API request, you should receive a response similar to this:
{
"status": "OK",
"results": [
{
"formatted_address": "1600 Pennsylvania Avenue NW, Washington, DC 20500, USA",
"geometry": {
"location": {
"lat": 38.8976763,
"lng": -77.0365298
},
"location_type": "ROOFTOP",
"viewport": {
"northeast": {
"lat": 38.8990252,
"lng": -77.0351808
},
"southwest": {
"lat": 38.8963273,
"lng": -77.0378787
}
}
},
"place_id": "ChIJGVtI4by3t4kRr51d_Qm_x58",
"types": [
"street_address"
],
"address_components": [
{
"long_name": "1600",
"short_name": "1600",
"types": ["street_number"]
},
{
"long_name": "Pennsylvania Avenue Northwest",
"short_name": "Pennsylvania Ave NW",
"types": ["route"]
},
{
"long_name": "Northwest Washington",
"short_name": "Northwest Washington",
"types": ["neighborhood", "political"]
},
{
"long_name": "Washington",
"short_name": "Washington",
"types": ["locality", "political"]
},
{
"long_name": "District of Columbia",
"short_name": "DC",
"types": ["administrative_area_level_1", "political"]
},
{
"long_name": "United States",
"short_name": "US",
"types": ["country", "political"]
},
{
"long_name": "20500",
"short_name": "20500",
"types": ["postal_code"]
}
]
}
]
}
Let's break down the key parts of this response:
- status: "OK" indicates that the request was successful.
- results: An array of geocoding results (addresses matching your query).
- formatted_address: The human-readable address.
- geometry.location: The latitude and longitude coordinates of the address.
- place_id: A unique identifier for this location that you can use in other Nexus APIs.
- address_components: Detailed components of the address (street, city, etc.).
This information can now be used in your application, such as displaying the location on a map or calculating routes to/from this location.
Display the Location on a Map
Now that we have the coordinates, let's take it a step further and display the location on a map using the Nexus Maps JavaScript SDK.
Create a new HTML file called map-example.html with the following code:
<!DOCTYPE html>
<html>
<head>
<title>Nexus Map Example</title>
<style>
body, html { height: 100%; margin: 0; padding: 0; }
#map { height: 100%; width: 100%; }
.info-panel {
position: absolute;
top: 10px;
left: 10px;
background: white;
padding: 10px;
border-radius: 4px;
box-shadow: 0 2px 6px rgba(0,0,0,0.3);
max-width: 300px;
}
</style>
</head>
<body>
<div id="map"></div>
<div class="info-panel">
<h2>Location Details</h2>
<div id="location-details">Loading...</div>
</div>
<!-- Nexus Maps SDK -->
<script src="https://maps.nexus-platform.com/sdk/v2/nexus-maps.js?key=YOUR_API_KEY"></script>
<script>
// Replace with your actual API key
const apiKey = 'YOUR_API_KEY';
// Initialize the map once the SDK is loaded
function initMap() {
// Create a map centered on the initial location
const map = new nexus.maps.Map(document.getElementById('map'), {
center: { lat: 38.8976763, lng: -77.0365298 }, // White House coordinates
zoom: 16,
style: 'standard'
});
// Add a marker for the location
const marker = new nexus.maps.Marker({
position: { lat: 38.8976763, lng: -77.0365298 },
map: map,
title: 'The White House',
animation: nexus.maps.Animation.DROP
});
// Add an info window
const infoWindow = new nexus.maps.InfoWindow({
content: '<h3>The White House</h3><p>1600 Pennsylvania Avenue NW, Washington, DC</p>'
});
// Open info window when marker is clicked
marker.addListener('click', () => {
infoWindow.open(map, marker);
});
// Update location details panel
document.getElementById('location-details').innerHTML = `
<p><strong>Address:</strong> 1600 Pennsylvania Avenue NW, Washington, DC 20500, USA</p>
<p><strong>Coordinates:</strong> Latitude: 38.8976763, Longitude: -77.0365298</p>
<p>Click on the marker to see more information.</p>
`;
}
// Load the map when the page is ready
window.onload = initMap;
</script>
</body>
</html>
Replace both instances of YOUR_API_KEY with the API key you created in Step 1.
Open the HTML file in your browser to see the map with the White House marker.
Next Steps
Congratulations! You've successfully made your first Nexus API request and displayed the results on a map. Here are some next steps to continue your journey with the Nexus platform:
- Explore our API Documentation to learn about all available endpoints
- Try out our SDK Libraries for your preferred programming language
- View Code Examples for more complex implementations
- Join our Developer Community to connect with other developers