{"id":7090,"date":"2024-08-19T17:46:27","date_gmt":"2024-08-19T15:46:27","guid":{"rendered":"https:\/\/betterqa.co\/?p=7090"},"modified":"2026-02-05T22:56:47","modified_gmt":"2026-02-05T20:56:47","slug":"automating-api-testing-with-cypress","status":"publish","type":"post","link":"https:\/\/betterqa.co\/automating-api-testing-with-cypress\/","title":{"rendered":"Automating API Testing with Cypress"},"content":{"rendered":"\t\t<div data-elementor-type=\"wp-post\" data-elementor-id=\"7090\" class=\"elementor elementor-7090\" data-elementor-post-type=\"post\">\n\t\t\t\t\t\t<section class=\"elementor-section elementor-top-section elementor-element elementor-element-773a26d elementor-section-full_width elementor-section-height-default elementor-section-height-default\" data-id=\"773a26d\" data-element_type=\"section\" data-e-type=\"section\">\n\t\t\t\t\t\t<div class=\"elementor-container elementor-column-gap-default\">\n\t\t\t\t\t<div class=\"elementor-column elementor-col-100 elementor-top-column elementor-element elementor-element-6171478\" data-id=\"6171478\" data-element_type=\"column\" data-e-type=\"column\">\n\t\t\t<div class=\"elementor-widget-wrap elementor-element-populated\">\n\t\t\t\t\t\t<div class=\"elementor-element elementor-element-1ab2210 elementor-widget elementor-widget-html\" data-id=\"1ab2210\" data-element_type=\"widget\" data-e-type=\"widget\" data-widget_type=\"html.default\">\n\t\t\t\t<div class=\"elementor-widget-container\">\n\t\t\t\t\t<style>\n    :root {\n      --bqa-purple: #9152DE;\n      --bqa-deep-purple: #5F29A1;\n      --bqa-blue: #204782;\n      --bqa-light-bg: #f8f9fa;\n      --bqa-border: #e0e0e0;\n      --bqa-green: #28a745;\n    }\n    * { box-sizing: border-box; margin: 0; padding: 0; }\n    body { font-family: 'Roboto', sans-serif; line-height: 1.7; color: #333; background: #fff; }\n    .bqa-article { max-width: 100%; margin: 0 auto; padding: 40px 20px; }\n    .bqa-article h1 { font-family: 'Jost', sans-serif; font-size: 2.2rem; font-weight: 600; color: #1a1a1a; margin-bottom: 1rem; line-height: 1.3; }\n    .bqa-article h2 { font-family: 'Jost', sans-serif; font-size: 1.5rem; font-weight: 600; color: var(--bqa-deep-purple); margin: 2.5rem 0 1rem; padding-bottom: 0.5rem; border-bottom: 2px solid var(--bqa-purple); }\n    .bqa-article h3 { font-family: 'Jost', sans-serif; font-size: 1.2rem; font-weight: 600; color: #1a1a1a; margin: 1.5rem 0 0.75rem; }\n    .bqa-article p { margin-bottom: 1rem; }\n    .bqa-article ul, .bqa-article ol { margin: 1rem 0 1.5rem 1.5rem; }\n    .bqa-article li { margin-bottom: 0.5rem; }\n    .bqa-article a { color: var(--bqa-purple); text-decoration: none; }\n    .bqa-article a:hover { text-decoration: underline; }\n    .bqa-article strong { font-weight: 500; }\n    .bqa-article code { background: #f4f4f4; padding: 2px 6px; border-radius: 3px; font-family: 'Fira Code', monospace; font-size: 0.9em; }\n\n    \/* Stats row *\/\n    .bqa-stats-row { display: flex; gap: 1rem; margin: 2rem 0; flex-wrap: wrap; }\n    .bqa-stat { flex: 1; min-width: 150px; background: linear-gradient(135deg, var(--bqa-deep-purple), var(--bqa-purple)); color: #fff; padding: 1.25rem; border-radius: 8px; text-align: center; }\n    .bqa-stat-value { display: block; font-family: 'Jost', sans-serif; font-size: 1.8rem; font-weight: 600; }\n    .bqa-stat-label { display: block; font-size: 0.85rem; opacity: 0.9; margin-top: 0.25rem; }\n\n    \/* Code block *\/\n    .bqa-code { background: #1e1e1e; color: #d4d4d4; padding: 1.25rem; border-radius: 8px; margin: 1rem 0 1.5rem; overflow-x: auto; font-family: 'Fira Code', monospace; font-size: 0.85rem; line-height: 1.5; }\n    .bqa-code-label { background: var(--bqa-purple); color: #fff; font-size: 0.75rem; padding: 0.25rem 0.75rem; border-radius: 4px 4px 0 0; display: inline-block; margin-bottom: -8px; position: relative; z-index: 1; }\n    .bqa-code .comment { color: #6a9955; }\n    .bqa-code .keyword { color: #569cd6; }\n    .bqa-code .string { color: #ce9178; }\n    .bqa-code .function { color: #dcdcaa; }\n\n    \/* Highlight box *\/\n    .bqa-highlight { background: var(--bqa-light-bg); border-left: 4px solid var(--bqa-purple); padding: 1.25rem 1.5rem; margin: 1.5rem 0; border-radius: 0 8px 8px 0; }\n    .bqa-highlight p:last-child { margin-bottom: 0; }\n\n    \/* Spec card *\/\n    .bqa-spec-card { background: #fff; border: 1px solid var(--bqa-border); border-radius: 8px; padding: 1.5rem; margin: 1.5rem 0; position: relative; }\n    .bqa-spec-card::before { content: ''; position: absolute; top: 0; left: 0; width: 12px; height: 12px; border-top: 2px solid var(--bqa-purple); border-left: 2px solid var(--bqa-purple); }\n    .bqa-spec-card::after { content: ''; position: absolute; top: 0; right: 0; width: 12px; height: 12px; border-top: 2px solid var(--bqa-purple); border-right: 2px solid var(--bqa-purple); }\n    .bqa-spec-card h3 { margin-top: 0; }\n\n    \/* Comparison boxes *\/\n    .bqa-compare { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; margin: 1.5rem 0; }\n    .bqa-compare-box { padding: 1.25rem; border-radius: 8px; }\n    .bqa-compare-box.yes { background: #e8f5e9; border: 1px solid var(--bqa-green); }\n    .bqa-compare-box.no { background: #fef3e8; border: 1px solid #ff9800; }\n    .bqa-compare-box h4 { margin: 0 0 0.75rem; font-size: 1rem; }\n    .bqa-compare-box.yes h4 { color: #2e7d32; }\n    .bqa-compare-box.no h4 { color: #e65100; }\n    .bqa-compare-box ul { margin: 0; padding-left: 1.25rem; font-size: 0.9rem; }\n    .bqa-compare-box li { margin-bottom: 0.35rem; }\n\n    \/* File tree *\/\n    .bqa-filetree { background: #f8f9fa; border: 1px solid var(--bqa-border); border-radius: 8px; padding: 1rem 1.5rem; margin: 1rem 0 1.5rem; font-family: 'Fira Code', monospace; font-size: 0.85rem; }\n    .bqa-filetree code { background: none; padding: 0; }\n\n    \/* Tip box *\/\n    .bqa-tip { background: #e3f2fd; border: 1px solid #2196f3; border-radius: 8px; padding: 1.25rem 1.5rem; margin: 1.5rem 0; }\n    .bqa-tip strong { color: #1565c0; }\n\n    \/* CTA *\/\n    .bqa-cta { background: linear-gradient(135deg, var(--bqa-deep-purple), var(--bqa-blue)); color: #fff; padding: 2rem; border-radius: 12px; margin: 2.5rem 0; text-align: center; }\n    .bqa-cta p { color: #fff; margin-bottom: 1rem; }\n    .bqa-cta a { display: inline-block; background: #fff; color: var(--bqa-deep-purple); padding: 0.75rem 2rem; border-radius: 6px; font-weight: 500; text-decoration: none; }\n    .bqa-cta a:hover { background: #f0f0f0; text-decoration: none; }\n\n    @media (max-width: 600px) {\n      .bqa-article h1 { font-size: 1.75rem; }\n      .bqa-stats-row { flex-direction: column; }\n      .bqa-stat { min-width: 100%; }\n      .bqa-compare { grid-template-columns: 1fr; }\n    }\n  <\/style>\n\n<div class=\"bqa-article\">\n\n<h1>Automating API testing with Cypress - practical guide with examples<\/h1>\n\n<div class=\"bqa-stats-row\">\n  <div class=\"bqa-stat\">\n    <span class=\"bqa-stat-value\">cy.request()<\/span>\n    <span class=\"bqa-stat-label\">Core API method<\/span>\n  <\/div>\n  <div class=\"bqa-stat\">\n    <span class=\"bqa-stat-value\">Chai<\/span>\n    <span class=\"bqa-stat-label\">Built-in assertions<\/span>\n  <\/div>\n  <div class=\"bqa-stat\">\n    <span class=\"bqa-stat-value\">CI\/CD<\/span>\n    <span class=\"bqa-stat-label\">Ready<\/span>\n  <\/div>\n<\/div>\n\n<h2>Why use Cypress for API testing?<\/h2>\n\n<p>Cypress is primarily known as an end-to-end UI testing tool, but its <code>cy.request()<\/code> command makes it a solid choice for API testing too. If your team already uses Cypress for frontend tests, adding API tests to the same framework avoids the overhead of maintaining a separate tool.<\/p>\n\n<div class=\"bqa-highlight\">\n  <p><strong>Advantages of Cypress for API testing (v15+):<\/strong><\/p>\n  <ul>\n    <li>Tests run in the same framework as your E2E tests<\/li>\n    <li>Built-in retry logic and assertions via Chai<\/li>\n    <li>Easy integration with CI\/CD pipelines<\/li>\n    <li>Network request interception with <code>cy.intercept()<\/code> for mocking<\/li>\n    <li>Automatic cookie and session management<\/li>\n    <li>Cypress Studio included by default for recording tests<\/li>\n  <\/ul>\n<\/div>\n\n<h2>Basic API test with cy.request()<\/h2>\n\n<p>Here is a simple test that hits a REST API and validates the response:<\/p>\n\n<div class=\"bqa-code-label\">users.cy.js<\/div>\n<pre class=\"bqa-code\">describe('Users API', () => {\n  it('returns a list of users', () => {\n    cy.request('GET', '\/api\/users').then((response) => {\n      expect(response.status).to.eq(200);\n      expect(response.body).to.be.an('array');\n      expect(response.body.length).to.be.greaterThan(0);\n      expect(response.body[0]).to.have.property('id');\n      expect(response.body[0]).to.have.property('email');\n    });\n  });\n\n  it('creates a new user', () => {\n    cy.request({\n      method: 'POST',\n      url: '\/api\/users',\n      body: {\n        name: 'Test User',\n        email: 'test@example.com',\n      },\n    }).then((response) => {\n      expect(response.status).to.eq(201);\n      expect(response.body.name).to.eq('Test User');\n      expect(response.body.id).to.be.a('number');\n    });\n  });\n});<\/pre>\n\n<h2>Testing with authentication<\/h2>\n\n<h3>Bearer token authentication<\/h3>\n\n<div class=\"bqa-code-label\">auth.cy.js<\/div>\n<pre class=\"bqa-code\">describe('Protected API', () => {\n  let authToken;\n\n  before(() => {\n    cy.request({\n      method: 'POST',\n      url: '\/api\/auth\/login',\n      body: {\n        email: Cypress.env('TEST_USER_EMAIL'),\n        password: Cypress.env('TEST_USER_PASSWORD'),\n      },\n    }).then((response) => {\n      authToken = response.body.token;\n    });\n  });\n\n  it('accesses protected resource', () => {\n    cy.request({\n      method: 'GET',\n      url: '\/api\/profile',\n      headers: {\n        Authorization: `Bearer ${authToken}`,\n      },\n    }).then((response) => {\n      expect(response.status).to.eq(200);\n      expect(response.body.email).to.eq(Cypress.env('TEST_USER_EMAIL'));\n    });\n  });\n\n  it('rejects requests without token', () => {\n    cy.request({\n      method: 'GET',\n      url: '\/api\/profile',\n      failOnStatusCode: false,\n    }).then((response) => {\n      expect(response.status).to.eq(401);\n    });\n  });\n});<\/pre>\n\n<div class=\"bqa-tip\">\n  <strong>Tip:<\/strong> Store credentials in <code>cypress.env.json<\/code> (add it to <code>.gitignore<\/code>) or pass them as environment variables in CI.\n<\/div>\n\n<h2>Validating response schemas<\/h2>\n\n<p>As your API evolves, response structures can change unexpectedly. Schema validation catches these regressions:<\/p>\n\n<div class=\"bqa-code-label\">schema.cy.js<\/div>\n<pre class=\"bqa-code\">it('user response matches expected schema', () => {\n  cy.request('GET', '\/api\/users\/1').then((response) => {\n    expect(response.body).to.have.all.keys(\n      'id', 'name', 'email', 'created_at', 'role'\n    );\n    expect(response.body.id).to.be.a('number');\n    expect(response.body.name).to.be.a('string');\n    expect(response.body.email).to.match(\/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$\/);\n    expect(response.body.role).to.be.oneOf(['admin', 'user', 'editor']);\n  });\n});<\/pre>\n\n<p>For more complex schema validation, install <code>chai-json-schema<\/code> and define JSON Schema objects.<\/p>\n\n<h2>Testing error handling<\/h2>\n\n<p>Good API tests cover failure cases too:<\/p>\n\n<div class=\"bqa-code-label\">errors.cy.js<\/div>\n<pre class=\"bqa-code\">describe('Error handling', () => {\n  it('returns 404 for non-existent resource', () => {\n    cy.request({\n      method: 'GET',\n      url: '\/api\/users\/999999',\n      failOnStatusCode: false,\n    }).then((response) => {\n      expect(response.status).to.eq(404);\n      expect(response.body).to.have.property('error');\n    });\n  });\n\n  it('returns 400 for invalid input', () => {\n    cy.request({\n      method: 'POST',\n      url: '\/api\/users',\n      body: { name: '' },\n      failOnStatusCode: false,\n    }).then((response) => {\n      expect(response.status).to.eq(400);\n      expect(response.body.errors).to.be.an('array');\n    });\n  });\n});<\/pre>\n\n<div class=\"bqa-tip\">\n  <strong>Note:<\/strong> Use <code>failOnStatusCode: false<\/code> when you expect non-2xx responses. Without it, Cypress treats any non-2xx status as a test failure.\n<\/div>\n\n<h2>Mocking APIs with cy.intercept()<\/h2>\n\n<p>When testing the frontend, you often want to control API responses. <code>cy.intercept()<\/code> lets you mock, stub, or modify network requests:<\/p>\n\n<div class=\"bqa-code-label\">mocking.cy.js<\/div>\n<pre class=\"bqa-code\">it('displays error message when API fails', () => {\n  cy.intercept('GET', '\/api\/users', {\n    statusCode: 500,\n    body: { error: 'Internal Server Error' },\n  }).as('getUsers');\n\n  cy.visit('\/users');\n  cy.wait('@getUsers');\n  cy.contains('Something went wrong').should('be.visible');\n});\n\nit('displays empty state when no data', () => {\n  cy.intercept('GET', '\/api\/users', {\n    statusCode: 200,\n    body: [],\n  }).as('getUsers');\n\n  cy.visit('\/users');\n  cy.wait('@getUsers');\n  cy.contains('No users found').should('be.visible');\n});<\/pre>\n\n<p>This is useful for testing edge cases that are hard to reproduce with a real backend.<\/p>\n\n<h2>Organizing API tests<\/h2>\n\n<p>For larger test suites, structure your API tests by resource:<\/p>\n\n<div class=\"bqa-filetree\">\n<code>cypress\/\n  e2e\/\n    api\/\n      users.cy.js\n      auth.cy.js\n      orders.cy.js\n      payments.cy.js\n    ui\/\n      login.cy.js\n      dashboard.cy.js\n  support\/\n    commands.js    # Custom commands for common API calls<\/code>\n<\/div>\n\n<p>Create custom commands for repeated API operations:<\/p>\n\n<div class=\"bqa-code-label\">cypress\/support\/commands.js<\/div>\n<pre class=\"bqa-code\">Cypress.Commands.add('apiLogin', (email, password) => {\n  return cy.request({\n    method: 'POST',\n    url: '\/api\/auth\/login',\n    body: { email, password },\n  }).then((response) => {\n    window.localStorage.setItem('token', response.body.token);\n    return response.body.token;\n  });\n});\n\n\/\/ In tests:\ncy.apiLogin('test@example.com', 'password123');<\/pre>\n\n<h2>Running in CI\/CD<\/h2>\n\n<p>Add Cypress API tests to your pipeline. They run fast since they do not need a browser:<\/p>\n\n<div class=\"bqa-code-label\">GitHub Actions<\/div>\n<pre class=\"bqa-code\">api-tests:\n  runs-on: ubuntu-latest\n  steps:\n    - uses: actions\/checkout@v4\n    - run: npm install\n    - run: npx cypress run --spec \"cypress\/e2e\/api\/**\"\n      env:\n        CYPRESS_BASE_URL: ${{ secrets.API_BASE_URL }}\n        CYPRESS_TEST_USER_EMAIL: ${{ secrets.TEST_EMAIL }}\n        CYPRESS_TEST_USER_PASSWORD: ${{ secrets.TEST_PASSWORD }}<\/pre>\n\n<h2>When to use Cypress vs dedicated API tools<\/h2>\n\n<div class=\"bqa-compare\">\n  <div class=\"bqa-compare-box yes\">\n    <h4>Use Cypress when:<\/h4>\n    <ul>\n      <li>Team already uses Cypress for E2E<\/li>\n      <li>Need API + UI tests in one framework<\/li>\n      <li>Want to combine API setup with UI assertions<\/li>\n    <\/ul>\n  <\/div>\n  <div class=\"bqa-compare-box no\">\n    <h4>Use Postman\/REST Assured when:<\/h4>\n    <ul>\n      <li>Need complex assertion chains<\/li>\n      <li>Testing APIs without frontend<\/li>\n      <li>Need API documentation alongside tests<\/li>\n      <li>No Node.js environment available<\/li>\n    <\/ul>\n  <\/div>\n<\/div>\n\n<p>Both approaches are valid. The best choice depends on your team's existing stack and testing goals.<\/p>\n\n<div class=\"bqa-cta\">\n  <p>For teams setting up API testing from scratch, BetterQA's automation engineers can help design a testing strategy that fits your architecture and CI\/CD pipeline.<\/p>\n  <a href=\"https:\/\/betterqa.co\/software-testing-services\/test-automation\/\">Talk to our team<\/a>\n<\/div>\n\n<\/div>\n\t\t\t\t<\/div>\n\t\t\t\t<\/div>\n\t\t\t\t\t<\/div>\n\t\t<\/div>\n\t\t\t\t\t<\/div>\n\t\t<\/section>\n\t\t\t\t<\/div>\n\t\t","protected":false},"excerpt":{"rendered":"<p>Automating API testing with Cypress. Step-by-step guide to API test automation for reliable backend coverage.<\/p>\n","protected":false},"author":33,"featured_media":10663,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[1004,84],"tags":[1127,1128,1037,1119,1120,1126,1050,951,969],"class_list":["post-7090","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-automation-techniques-and-challenges","category-automation-testing","tag-api-testing","tag-cypress","tag-independent-software-testing-services","tag-offshore-software-testing","tag-offshore-testing","tag-qa-award","tag-qa-testing","tag-quality-asssurance","tag-quality-control"],"acf":[],"_links":{"self":[{"href":"https:\/\/betterqa.co\/wp-json\/wp\/v2\/posts\/7090","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/betterqa.co\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/betterqa.co\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/betterqa.co\/wp-json\/wp\/v2\/users\/33"}],"replies":[{"embeddable":true,"href":"https:\/\/betterqa.co\/wp-json\/wp\/v2\/comments?post=7090"}],"version-history":[{"count":0,"href":"https:\/\/betterqa.co\/wp-json\/wp\/v2\/posts\/7090\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/betterqa.co\/wp-json\/wp\/v2\/media\/10663"}],"wp:attachment":[{"href":"https:\/\/betterqa.co\/wp-json\/wp\/v2\/media?parent=7090"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/betterqa.co\/wp-json\/wp\/v2\/categories?post=7090"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/betterqa.co\/wp-json\/wp\/v2\/tags?post=7090"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}