Skip to main content
Glama

execute_api_request

Execute API requests to specific endpoints using HTTP methods, paths, parameters, headers, and body data for testing and exploration.

Instructions

Execute an API request to a specific endpoint

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
methodYesHTTP method (GET, POST, PUT, DELETE, etc.)
pathYesThe endpoint path (e.g., '/users/123')
paramsNoQuery parameters as key-value pairs
bodyNoRequest body as a JSON object (for POST/PUT/PATCH)
headersNoCustom headers as key-value pairs

Implementation Reference

  • The core handler function that performs the actual API request using fetch. It builds the URL, sets headers including auth, handles request body, logs details, manages token refresh on 401, and processes the response.
    async function executeApiRequest(method, path, params = {}, body = null, headers = {}) { try { const url = buildUrl(path, params); const requestOptions = { method: method.toUpperCase(), headers: { 'Accept': 'application/json', ...headers } }; if (['POST', 'PUT', 'PATCH'].includes(method.toUpperCase()) && body) { requestOptions.headers['Content-Type'] = 'application/json'; requestOptions.body = JSON.stringify(body); } const isAuthEndpoint = isAuthenticationEndpoint(path); if (isAuthEndpoint) { log.info(`Auth endpoint detected: ${path}. Not adding Authorization header.`); if (!body && ['POST', 'PUT'].includes(method.toUpperCase()) && API_USERNAME && API_PASSWORD) { const isSignUp = isSignUpEndpoint(path); if (!isSignUp) { requestOptions.headers['Content-Type'] = 'application/json'; requestOptions.body = JSON.stringify({ username: API_USERNAME, password: API_PASSWORD }); log.info(`Auto-injecting default credentials for authentication endpoint`); } else { log.warning(`Sign-up/register endpoint detected: ${path}. Skipping auto-injection of default credentials. Use unique credentials for registration.`); } } } else { if (!headers.Authorization) { if (authTokens.apiAccess) { requestOptions.headers['Authorization'] = `Bearer ${authTokens.apiAccess}`; log.info(`Using stored API token for authorization`); } else if (API_KEY) { requestOptions.headers['Authorization'] = `Bearer ${API_KEY}`; log.info(`Using configured API key for authorization`); } } } log.api(method.toUpperCase(), url); log.debug(`Request headers: ${JSON.stringify(maskSensitiveHeaders(requestOptions.headers))}`); if (requestOptions.body) { const logBody = JSON.parse(requestOptions.body); const sensitiveFields = ['password', 'secret', 'token', 'key', 'apiKey', 'api_key']; for (const field of sensitiveFields) { if (field in logBody) { logBody[field] = '********'; } } log.debug(`Request body: ${JSON.stringify(logBody, null, 2)}`); } const response = await fetch(url, requestOptions); if (response.status === 401 && !isAuthEndpoint) { log.warning(`Received 401 Unauthorized. Attempting to refresh token...`); if (swaggerDoc) { const authEndpoint = findAuthEndpoint(); if (authEndpoint) { log.info(`Found auth endpoint: ${authEndpoint.method} ${authEndpoint.path}`); const authResponse = await executeApiRequest( authEndpoint.method, authEndpoint.path, {}, { username: API_USERNAME, password: API_PASSWORD }, {} ); if (authResponse.status >= 200 && authResponse.status < 300) { log.success(`Successfully refreshed token`); if (authTokens.apiAccess) { requestOptions.headers['Authorization'] = `Bearer ${authTokens.apiAccess}`; log.info(`Retrying request with new token`); const retryResponse = await fetch(url, requestOptions); return await processApiResponse(retryResponse, path, url, method); } } } else { log.warning(`Could not find suitable auth endpoint to refresh token`); } } } return await processApiResponse(response, path, url, method); } catch (error) { log.error(`Error executing API request: ${error.message}`); throw new Error(`API request failed: ${error.message}`); } }
  • The tool definition including name, description, and input schema for validating parameters to the execute_api_request tool.
    { name: "execute_api_request", description: "Execute an API request to a specific endpoint", inputSchema: { type: "object", properties: { method: { type: "string", description: "HTTP method (GET, POST, PUT, DELETE, etc.)" }, path: { type: "string", description: "The endpoint path (e.g., '/users/123')" }, params: { type: "object", description: "Query parameters as key-value pairs" }, body: { type: "object", description: "Request body as a JSON object (for POST/PUT/PATCH)" }, headers: { type: "object", description: "Custom headers as key-value pairs" } }, required: ["method", "path"], }, },
  • The registration handler within the CallToolRequestSchema switch statement that extracts arguments and calls the executeApiRequest function.
    case "execute_api_request": { const method = request.params.arguments?.method; const path = request.params.arguments?.path; const params = request.params.arguments?.params || {}; const body = request.params.arguments?.body || null; const headers = request.params.arguments?.headers || {}; if (!method || !path) { throw new Error("Method and path are required"); } try { const result = await executeApiRequest(method, path, params, body, headers); return { content: [{ type: "text", text: JSON.stringify(result) }], isError: false, }; } catch (error) { throw new Error(`Failed to execute API request: ${error.message}`); } }

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/amrsa1/swagger-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server